Process CSV Into Array With Column Headings For Key

后端 未结 9 2379
星月不相逢
星月不相逢 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:16

    Try with this code:

    $query = "SELECT * FROM datashep_AMS.COMPLETE_APPLICATIONS";
    $export= mysql_query($query);
    $first = true;
    $temp = $export[0];
    //echo "<pre>"; print_r($first); exit;
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=file.csv');
    header('Pragma: no-cache');
    header("Expires: 0");
    
    $outstream = fopen("php://output", "w");
    
    
    
    foreach($export as $result)
    {
        if($first){
            $titles = array();
            foreach($temp as $key=>$val){
                $titles[] = $key;
            }
            //print_r ($titles);exit;
            fputcsv($outstream, $titles);
        }
        $first = false;
        fputcsv($outstream, $result);
    }
    
    fclose($outstream);
    

    Thanks

    0 讨论(0)
  • 2020-11-29 04:18

    Try this

    $csv = array_map("str_getcsv", file('file.csv', FILE_SKIP_EMPTY_LINES));    
    $header = array_shift($csv); // get header from array
    
    foreach ($csv as $key => $value) {    
        $csv[$key] = array_combine($header, $value);
        var_dump($csv[$key]['Model']);
    }
    
    var_dump($csv);
    
    0 讨论(0)
  • 2020-11-29 04:19
    $csv_data = array_map('str_getcsv', file('Book.csv'));// reads the csv file in php array
    $csv_header = $csv_data[0];//creates a copy of csv header array
    unset($csv_data[0]);//removes the header from $csv_data since no longer needed
    foreach($csv_data as $row){
        $row = array_combine($csv_header, $row);// adds header to each row as key
        var_dump($row);//do something here with each row
    }
    
    0 讨论(0)
提交回复
热议问题