我使用此代码导入基本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"
} ],
} ]
答案 0 :(得分:0)
对于每个$row
,
@$cardCodes[$row[1]]['payment_sum'] += $row[3];
@$cardCodes[$row[1]]['details'][] = array(
'DocNum' => $row[0],
'InvPayAmnt' => $row[3],
'PmntDate' => $row[4?],
);
格式不完全相同但已编入索引,并且适用于js中的for x in y
循环。