我有这个JSON数组,我将其解码为PHP数组,并想查看每个类别中总共售出了多少
[{
"categorycode": "W0000000391",
"grosssalesprice": "50.00"
},
{
"categorycode": "W0000000396",
"grosssalesprice": "170.00"
},
{
"categorycode": "W0000000391",
"grosssalesprice": "50.00"
},
{
"categorycode": "W0000000391",
"grosssalesprice": "55.00"
}]
,并希望获得
{
"categorycode": "W0000000391",
"grosssalesprice": "155.00"
},
{
"categorycode": "W0000000396",
"grosssalesprice": "170.00"
}
我尝试过,这给了我1个foreach元素入口,但是我如何追加这个数组中的每个项目呢?
foreach($jsonDecoded as $item) {
$sortedData[$item['categorycode']] = array(
'Konto' => $item['categorycode'],
'Beløb' => $item['grosssalesprice']
);
}
答案 0 :(得分:3)
$items = json_decode($json,true);
foreach($items as $item){
if(empty($totalInCategory[$item['categorycode']])){
$totalInCategory[$item['categorycode']] = 0.00;
}
$totalInCategory[$item['categorycode']] += $item['grosssalesprice'];
}
var_dump($totalInCategory);
应该这样做,并提出:
array(2) {
["W0000000391"]=>
float(155)
["W0000000396"]=>
float(170)
}
但是,要进一步匹配所需的格式:
foreach($items as $item){
if(empty($totalInCategory[$item['categorycode']]['grosssalesprice'])){
$totalInCategory[$item['categorycode']]['grosssalesprice'] = 0.00;
}
$totalInCategory[$item['categorycode']]['categorycode'] = $item['categorycode'];
$totalInCategory[$item['categorycode']]['grosssalesprice'] += $item['grosssalesprice'];
}
但是键必须是唯一的,因此您可以像这样保留它们或在结果数组上运行sort()
以将数组键重置为整数值