我正在使用fgetcsv从.csv(最初来自外部数据库)文件中读取数据。 .csv文件的第一行包含列名,以下行包含数据。 到目前为止我得到的是一个包含列名的数组,第二个数组包含.csv文件的行(每行作为数组)。 如何将第二个数组转换为关联数组,其中键是第一个数组中的列名?
// 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);
这是var_dump($ header):
数组(大小= 1) 0 => 数组(大小= 50) 0 =>字符串' KHK_EAN' (长度= 7) 1 => string' StyleNumber' (长度= 11) 2 => string' StyleName' (长度= 9) 3 =>字符串' Setname' (长度= 7) 4 => string' ColorNumber' (长度= 11) 5 =>字符串' ColorName' (长度= 9) 6 => string' StyleSize' (长度= 9) 7 =>字符串' KHK_Artikel' (长度= 11) 8 => string' PriceNew' (长度= 8) 9 => string' PriceSale' (长度= 9)
注意:有一个带有1个元素的顶层数组,其中包含另一个带有列名的数组。
$ rawData数组:
数组(大小= 3604) 0 => 数组(大小= 50) 0 =>字符串' 4055765008989' (长度= 13) 1 =>字符串' 201001001' (长度= 9) 2 =>字符串' ' (长度= 1) 3 =>字符串'访问3' (长度= 8) 4 =>字符串' 2942' (长度= 4) 5 => string' Blau / Marine' (长度= 11) 6 =>字符串' 1' (长度= 1) 7 =>字符串' 201001001-2942-1' (长度= 16) 8 =>字符串' 199,9' (长度= 5) 9 =>字符串' 199,9' (长度= 5) 1 => 数组(大小= 50) 0 =>字符串' 4055765008996' (长度= 13) 1 =>字符串' 201001001' (长度= 9) 2 =>字符串' ' (长度= 1) 3 =>字符串'访问3' (长度= 8) 4 => string' 3924' (长度= 4) 5 => string' Beige / Braun' (长度= 11) 6 =>字符串' 1' (长度= 1) 7 =>字符串' 201001001-3924-1' (长度= 16) 8 =>字符串' 199,9' (长度= 5) 9 =>字符串' 199,9' (长度= 5) 2 => 数组(大小= 50) 0 =>字符串' 4055765009047' (长度= 13) 1 =>字符串' 201002001' (长度= 9) 2 =>字符串' ' (长度= 1) 3 =>字符串'访问3' (长度= 8) 4 =>字符串' 2942' (长度= 4) 5 => string' Blau / Marine' (长度= 11) 6 =>字符串' 1' (长度= 1) 7 =>字符串' 201002001-2942-1' (长度= 16) 8 =>字符串' 179,9' (长度= 5) 9 =>字符串' 179,9' (长度= 5)
注意:与上面一样,嵌套数组,所以我不能使用array_combine()。 有什么建议吗?
答案 0 :(得分:1)
这是和这里一样的问题吗?为方便起见,将其复制在下方。
how do i parse a csv file to grab the column names first then the rows that relate to it?
要立即阅读所有内容,您可以使用:
$csv = array_map("str_getcsv", file("file1.csv",FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
要将所有行转换为友好的关联数组,您可以应用:
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}