I have a CSV file with headings in both the columns and rows that i need as an associative array and the examples i have tried on SO haven't worked for me.
The closest example i found was CSV to Associative Array but i couldn't print the data, so i must be missing something.
Any help would be appreciated
$all_rows = array();
$header = 1;//null; // has header
if (($handle = fopen($csv_file, "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($header === null) {
$header = $row;
continue;
}
$all_rows[] = array_combine($header, $row);
}
fclose($handle);
}
// CSV Example
// [FOOD][IN_Stock][On_Order]
// [Apples][1302][2304]
// [Oranges][4356][335]
foreach ($all_rows as $key => $value) {
// This prints ok based on the row number
echo $all_rows[$key]['Instock'];
// But i need to be able to call data based on the Food Type
echo $all_rows['Apples']['In_Stock'];
echo $all_rows['Apples']['On_order'];
echo $all_rows['Oranges']['In_Stock'];
echo $all_rows['Oranges']['On_order'];
}
I can print the data by calling the row number, but the data will not always be the same and therefore need to print based on the headers in the first column.
Added the printed Array as Requested:
Array
(
[0] => Array
(
[Food] => Apples
[In_Stock] => 6329
[On_Order] => 375
)
[1] => Array
(
[Food] => Pears
[In_Stock] => 3329
[On_Order] => 275
)
[2] => Array
(
[Food] => Oranges
[In_Stock] => 629
[On_Order] => 170
)
)
Encase anyone else needs it, this is what i used:
$csv = array();
foreach ($all_rows as $row) {
if($row) {
foreach($row as $key => $val) {
$csv[$val]['In_Stock'] = $row["In_Stock"];
$csv[$val]['On_order'] = $row["On_order"];
}
}
}