I am reading data from a .csv (which originally comes from an external database) file with fgetcsv. The first line of the .csv file contains the column names, the following rows contain the data. What I got so far is an array with the column names, and a second array with the rows of of the .csv file (each row as an array). How can I convert the second array to an associative array with keys being the column names from the first array?
// this is for Mac OS X
ini_set("auto_detect_line_endings", true);
// the name of the file to read
$fileName = 'WebArtikel_V1-modified.csv';
// open file (get handle to file)
$file = fopen($fileName, 'r');
// the array to store the csv's data
$rawData = array();
// the first line of the csv
$header = array();
$i = 0;
while (($line = fgetcsv($file, 4096, ";")) !== FALSE) {
//$line is an array of the csv elements
//print_r($line);
if($i == 0){
$header[] = $line;
} else {
$rawData[] = $line;
}
$i++;
}
fclose($file);
Here is the var_dump($header):
array (size=1) 0 => array (size=50) 0 => string 'KHK_EAN' (length=7) 1 => string 'StyleNumber' (length=11) 2 => string 'StyleName' (length=9) 3 => string 'Setname' (length=7) 4 => string 'ColorNumber' (length=11) 5 => string 'ColorName' (length=9) 6 => string 'StyleSize' (length=9) 7 => string 'KHK_Artikel' (length=11) 8 => string 'PriceNew' (length=8) 9 => string 'PriceSale' (length=9)
Note: there is a toplevel array with 1 element which contains another array with the column names.
The $rawData array:
array (size=3604) 0 => array (size=50) 0 => string '4055765008989' (length=13) 1 => string '201001001' (length=9) 2 => string ' ' (length=1) 3 => string 'ACCESS 3' (length=8) 4 => string '2942' (length=4) 5 => string 'Blau/Marine' (length=11) 6 => string '1' (length=1) 7 => string '201001001-2942-1' (length=16) 8 => string '199,9' (length=5) 9 => string '199,9' (length=5) 1 => array (size=50) 0 => string '4055765008996' (length=13) 1 => string '201001001' (length=9) 2 => string ' ' (length=1) 3 => string 'ACCESS 3' (length=8) 4 => string '3924' (length=4) 5 => string 'Beige/Braun' (length=11) 6 => string '1' (length=1) 7 => string '201001001-3924-1' (length=16) 8 => string '199,9' (length=5) 9 => string '199,9' (length=5) 2 => array (size=50) 0 => string '4055765009047' (length=13) 1 => string '201002001' (length=9) 2 => string ' ' (length=1) 3 => string 'ACCESS 3' (length=8) 4 => string '2942' (length=4) 5 => string 'Blau/Marine' (length=11) 6 => string '1' (length=1) 7 => string '201002001-2942-1' (length=16) 8 => string '179,9' (length=5) 9 => string '179,9' (length=5)
Note: same as above, nested arrays, so I can't use array_combine(). Any suggestions?