user393219
user393219

Reputation:

Create an array within an array using a string from key

I can't get past making what I think is a 2D Array in PHP. I'm using a CSV as source input and want to take one of the columns and split that into an array as well.

$csv = array_map("str_getcsv", file("data/data.csv", FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);

foreach ($csv as $i => $row) {

    $csv[$i] = array_combine($keys, $row);

    $linkto  = $csv[$i]['linkto'];
    // $linktoArray = explode(" ", $linkto);

    echo '<pre>';
    // print_r($linktoArray);
    echo '</pre>';

    $csv[$i] = array_combine($keys, $row);

}

$csv['timestamp'] = time();

echo '<pre>';
print_r($csv);
echo '</pre>';

Will output:

Array
(
    [0] => Array
        (
            [color] => 1
            [shape] => 0
            [label] => string
            [size] => 1
            [linkto] => 1 2 3
        )...

Using something similar to what I commented out, I'd love to see something like:

Array
(
    [0] => Array
        (
            [color] => 1
            [shape] => 0
            [label] => string
            [size] => 1
            [linkto] => Array
                (
                    [0]=>1
                    [1]=>2
                    [2]=>3
                )
        )...

However, right now I'm just getting an array before my containing array. Pardon my ignorance, I haven't had much experience past the front-end. Any suggestions? I'm sure this has been explained before, but I can't find the right terminology to utilize a search.

Upvotes: 0

Views: 76

Answers (2)

Anthony
Anthony

Reputation: 37045

Here is a modified example from the SplFileObject::fgetcsv documentation that might simplify your code enough to isolate what might be giving you issues:

$file = new SplFileObject("data/data.csv");
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
$header_row = ($file->fgetcsv());

foreach ($file as $row) {
$row = array_combine($header_row, $row);
    $row['linkto'] = explode(" ", $row['linkto']);
    $csv[] = $row;
}

print_r($csv);

Upvotes: 1

Styphon
Styphon

Reputation: 10447

It's fairly straight forward. All you need to do is this:

$linkto  = $csv[$i]['linkto'];
$linktoArray = explode(" ", $linkto);
$csv[$i]['linkto'] = $linktoArray;

After having read through your code again, you seem to be struggling with the concept of foreach. When you use foreach you don't access $csv[$i] like you have, you just use $row. Try something like:

//The & symbol means any changes made to $row inside the foreach will apply outside the foreach.
foreach($csv as $i => &$row) {
    $row['linkto'] = explode(" ", $row['linkto']);
}

That should be all you need, none of this array_combine stuff.

Upvotes: 1

Related Questions