Need to define a function that create a associative array from csv file using only php code (no jquery and mysql) with using foreachloop csv file data looks like below output expected as below [12] = > Array ([img] = > abc.jpg| [title] = > machine 1 [desc] = > description 1 [price] = > $25)
Expert Answer
run over the csv file line by line, and insert to array like: $array = $fields = array(); $i = 0; $handle = @fopen("file.csv", "r"); if ($handle) { while (($row = fgetcsv($handle, 4096)) !== false) { if (empty($fields)) { $fields = $row; continue; } foreach ($row as $k=>$value) { $array[$i][$fields[$k]] = $value; } $i++; } if (!feof($handle)) { echo "Error: unexpected fgets() failn"; } fclose($handle); }