Process CSV Into Array With Column Headings For Key

后端 未结 9 2512
星月不相逢
星月不相逢 2020-11-29 03:35

I have a CSV with the first row containing the field names. Example data is...

\"Make\",\"Model\",\"Note\"
\"Chevy\",\"1500\",\"loaded\"
\"Chevy\",\"2500\",         


        
9条回答
  •  野性不改
    2020-11-29 04:03

    At this point I'm assuming you've already solved the issue but thought I'd throw in a suggested way around this, probably not the best/most elegant solution but it does the trick:

    $row = 1;
    $array = array();
    $marray = array();
    $handle = fopen('file.csv', 'r');
    if ($handle !== FALSE) {
        while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
            if ($row === 1) {
                $num = count($data);
                for ($i = 0; $i < $num; $i++) {
                    array_push($array, $data[$i]);
                }
            }
            else {
                $c = 0;
                foreach ($array as $key) {
                    $marray[$row - 1][$key] = $data[$c];
                    $c++;
                }
            }
            $row++;
        }
        echo '
    ';
        print_r($marray);
        echo '
    '; }

提交回复
热议问题