Process CSV Into Array With Column Headings For Key

后端 未结 9 2523
星月不相逢
星月不相逢 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 03:57

    function processCsv($absolutePath)
    {
        $csv = array_map('str_getcsv', file($absolutePath));
        $headers = $csv[0];
        unset($csv[0]);
        $rowsWithKeys = [];
        foreach ($csv as $row) {
            $newRow = [];
            foreach ($headers as $k => $key) {
                $newRow[$key] = $row[$k];
            }
            $rowsWithKeys[] = $newRow;
        }
        return $rowsWithKeys;
    }
    

提交回复
热议问题