0

我有一个 CSV 文件,其内容是:

jobname1, address11, address12, address13, date
item11, chilled, 2kg
item12, chilled, 20kg
jobname2, address21, address22, address23, date
item21, chilled, 2kg
item22, chilled, 20kg

如何在 PHP 中将其解析为多维数组,item11并将item12其附加到jobname1数组的位置和位置?同样的,我希望item21anditem22被追加到jobname2数组中。的输出var_dump应该是这样的:

array[0] = jobname1
           address11
           address12
           address13
           date
           item[0] = item11
                     chilled
                     2kg
           item[1] = item12
                     chilled
                     20kg
array[1] = jobname2
           address21
           address22
           address23
           date
           item[0] = item21
                     chilled
                     2kg
           item[1] = item22
                     chilled
                     20kg
4

1 回答 1

0

你会使用这样的东西。

$fp = fopen("source.csv", "r");
$results  = array();
$curContext = null;

while ($rec = fgetcsv($fp)){
    switch (count($rec)){
         case 5:
             // header object
             if ($curContext){
                 $results[] = $curContext;
             }
             $curContext = $rec;
             $curContext["items"] = array();
             break;
         case 3:
             $curContext["items"][] = $rec;
             break;
    }
}
// push the last one onto the array
$results[] = $curContext;
于 2013-06-13T14:15:11.767 回答