0

我的 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

4

1 回答 1

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));
}
于 2013-11-05T15:51:04.643 回答