0

I read a csv file with my code and convert it into an array. This is my code:

$csv_data = array_map('str_getcsv', file('test123.csv'));
$csv_header = $csv_data[0];
unset($csv_data[0]);
foreach($csv_data as $row){
    $row = array_combine($csv_header, $row);
    echo '<pre>';
        print_r($row);
    echo '<pre>';
}

And that's the output:

Array
(
    [ID] => 1
    [article] => 000001
)

Array
(
    [ID] => 2
    [article] => 000002
)

I'd like the arrays to be in an array, like this:

Array
(
     [0] => Array
     (
         [ID] => 1
         [article] => 000001
     )

     [1] => Array
     (
         [ID] => 2
         [article] => 000002
     )

)

Anybody got an idea? It's important that the headers don't get lost.

Sternisic
  • 123
  • 1
  • 2
  • 10

2 Answers2

2

Change

$row = array_combine($csv_header, $row);

To

$rows[] = array_combine($csv_header, $row);

than use print_r($rows) after the loop.

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
1

You have to use & to update array at its address.

foreach($csv_data as &$row){ // check & to update at its address
    $row = array_combine($csv_header, $row);
    echo '<pre>';
        print_r($row);
    echo '<pre>';
}
print_r($csv_data); // you will get your expected data here
Rahul
  • 18,271
  • 7
  • 41
  • 60