0

我正在使用此代码导入基本 CSV,其中每一行代表一张发票。我希望这些发票按其中一列分组,并最终执行 json_encode 以生成具有父/子层次结构的 json。我该怎么做呢?

CSV

 ID      CardCode    sum            amount     
 165     BENV5271    100            100 
 026     BENV5635    509.85         287.33
 9025    BENV5635    509.85         222.52  

PHP

if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
    die('Error opening file'); 
}
 $headers = fgetcsv($handle, 1024, ',');
 $cardCodes = array();

 while ($row = fgetcsv($handle, 1024, ",")) {
    $cardCodes[] = array_combine($headers, $row);
}
fclose($handle);

JSON(目标)

 [ {
 "CardCode":"BENV5271", 
 "payment_sum": "100.00"
 "details": [ {
    "DocNum": "165",
    "InvPayAmnt": "100.00",
    "PmntDate": "2012-03-29"
  } ],

}, {
 "CardCode": "BENV5635",
 "payment_sum": "509.85"
 "details": [ {
     "DocNum": "026"  
     "InvPayAmnt": "287.33",
     "PmntDate": "2012-03-29"
   }, {
     "DocNum": "025",
     "InvPayAmnt": "222.52",
     "PmntDate": "2012-03-29"
   } ],
} ]
4

1 回答 1

0

对于每个$row,

@$cardCodes[$row[1]]['payment_sum'] += $row[3];
@$cardCodes[$row[1]]['details'][] = array(
    'DocNum' => $row[0],
    'InvPayAmnt' => $row[3],
    'PmntDate' => $row[4?],
);

格式不完全相同,但已编入索引,适用for x in y于 js 中的循环。

于 2012-06-05T15:09:41.207 回答