将逗号分隔的数组值循环到多维数组中

时间:2013-11-05 15:46:48

标签: php arrays multidimensional-array foreach explode

我的PHP应用程序会将选定的csv文件上传到内存中。然后使用str_getcsv将其转换为数组,如下所示。

//get file from session variable created in upload.php
$uploadedfile = str_getcsv($_SESSION['uploadedfile'], "\n");

//remove first two rows as these contain headers
unset($uploadedfile[0]);
unset($uploadedfile[1]);

数组目前看起来像这样:

array(4174) {
  [2]=>
string(180) "productID,ProductBarcode,brand,productType,productName"
  [3]=>
string(178) "productID,ProductBarcode,brand,productType,productName"

我需要遍历每一行并将逗号分隔值分解为多维数组。所以它看起来像这样:

array() {
 [row2]=>
   "productID => 001"
   "ProductBarcode=>101010"
   "brand=>apple"
   "productType=>notebook"
   "productName=>Macbook pro"
 [row3]=>
   "productID => 002"
   "ProductBarcode=>20202"
   "brand=>apple"
   "productType=>desktop"
   "productName=>iMac"
 }

我相信这个问题是要回答类似的事情,但没有提供答案: PHP: Parsing Comma-Separated Values Between Square Brackets into Multi-Dimensional Array

1 个答案:

答案 0 :(得分:1)

尝试使用file将文件行读入数组。然后将第一行用作array_shift的标题。之后只需循环并将该行读入带str_getcsv的数组并与标题组合:

$uploadedfile = file($_SESSION['uploadedfile'], FILE_IGNORE_NEW_LINES);
$headers = array_shift($uploadedfile);
unset($uploadedfile[0]);

foreach($uploadedfile as $line) {
    $data[] = array_combine($headers, str_getcsv($line));
}