Question & Answer: 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…..

associative array from csv file using only php code (no need to define a function that create iguery and mysal) with using toreacbleon csv file data looks like below product Id title machine1 description1 machine2 description2 machine3 description3 img price 12 abc.jpe 13 bsc.jp 14 fgb 25 25 25 output expected as below [12] => Array LImg] => abc.jpg| [title] => machine 1 [desal => description! [price] => $25)

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);
}
Still stressed from student homework?
Get quality assistance from academic writers!