CSV to Associative Array

前端 未结 6 1434
孤城傲影
孤城傲影 2020-11-28 05:58

I\'ve seen numerous examples on how to take a CSV file and then create an associative array with the headers as the keys.

For example:

Brand,Model,Pa         


        
6条回答
  •  天命终不由人
    2020-11-28 06:50

    Using fgetcsv() seems the most direct and sensible tool for the job.

    csv.csv contents:

    Brand,Model,Part,Test
    Honda,Civic,123,244
    Honda,Civic,135,434
    Toyota,Supra,511,664
    

    Code:

    $assoc_array = [];
    if (($handle = fopen("csv.csv", "r")) !== false) {                 // open for reading
        if (($data = fgetcsv($handle, 1000, ",")) !== false) {         // extract header data
            $keys = $data;                                             // save as keys
        }
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {      // loop remaining rows of data
            $assoc_array[] = array_combine($keys, $data);              // push associative subarrays
        }
        fclose($handle);                                               // close when done
    }
    echo "
    ";
        var_export($assoc_array);                                      // print to screen
    echo "
    ";

    Output:

    array (
      0 => 
      array (
        'Brand' => 'Honda',
        'Model' => 'Civic',
        'Part' => '123',
        'Test' => '244',
      ),
      1 => 
      array (
        'Brand' => 'Honda',
        'Model' => 'Civic',
        'Part' => '135',
        'Test' => '434',
      ),
      2 => 
      array (
        'Brand' => 'Toyota',
        'Model' => 'Supra',
        'Part' => '511',
        'Test' => '664',
      ),
    )
    

    Resource: http://php.net/manual/en/function.fgetcsv.php

提交回复
热议问题