我正在尝试在PHP中创建一个多维数组,其中内部数组对于以下示例CSV字符串$csv是关联的:
# Results from 2015-06-16 to 2015-06-16.
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48
第三行及以上格式的实际数据行数是可变的。我目前所做的是创建一个简单的多维数组:
$resultArray = str_getcsv($csv, PHP_EOL);//parse the rows
array_shift($resultArray);//shift out results first row: date info
array_shift($resultArray);//shift out results new first row: field labels
foreach($resultArray as &$row) {//parse the items in rows
$row = str_getcsv($row, ",", '"');//removes the '"' field enclosure?
}//foreach
这创建了一个功能性的多维数组,但我无法弄清如何使内部数组关联起来,以便我可以使用来自预期使用的数组中的文本友好键访问它们:
$rowFieldKeysArray = array('date', 'time', 'label', 'artist', 'composer', 'album', 'title', 'duration');
我相信有一种简单的PHP方法可以将关键字数组用作关联数组的键,但我不确定如何实现。我怀疑我需要做类似于以下的事情:
foreach($resultArray as $rowKey => &$row) {
$row[$rowFieldKeysArray[$rowKey]] = str_getcsv($row, ",", '"');
}//foreach
但是这会产生一个“警告:非法字符串偏移量'date'[...]”的错误。
我应该怎么做?
编辑:根据Andrew评论中提供的链接和我接受的答案中提供的信息,我能够使用以下有效的代码解决这个问题。
$resultArray = str_getcsv($csv, PHP_EOL);//parse the rows
array_shift($resultArray);//shift out results first row: date info
$rowFieldKeysArray = str_getcsv( array_shift($resultArray), "," );//shift out results new first row: field labels into field key name array
//array('date', 'time', 'label', 'artist', 'composer', 'album', 'title', 'duration');//array of Key field names for associative array
// [0] [1] [2] [3] [4] [5] [6] [7] //key index
foreach($resultArray as &$row) {//parse the items in rows
$row = array_combine($rowFieldKeysArray, str_getcsv($row, ",", '"'));//array_combine replaces numeric indexes with key field labels
}//foreach
谢谢你!