[英]Sum product price in array and group
i have this JSON array i decode into a PHP array and would like to check how much have been sold in total in each category 我有这个JSON数组,我将其解码为PHP数组,并想检查每个类别中总共卖出了多少
[{
"categorycode": "W0000000391",
"grosssalesprice": "50.00"
},
{
"categorycode": "W0000000396",
"grosssalesprice": "170.00"
},
{
"categorycode": "W0000000391",
"grosssalesprice": "50.00"
},
{
"categorycode": "W0000000391",
"grosssalesprice": "55.00"
}]
and would like to get 并希望得到
{
"categorycode": "W0000000391",
"grosssalesprice": "155.00"
},
{
"categorycode": "W0000000396",
"grosssalesprice": "170.00"
}
I tried, this gives me 1 entry foreach element, but how do i append every item in this array? 我试过了,这给了我1个foreach元素,但是我怎么追加这个数组中的每个项目呢?
foreach($jsonDecoded as $item) {
$sortedData[$item['categorycode']] = array(
'Konto' => $item['categorycode'],
'Beløb' => $item['grosssalesprice']
);
}
$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);
Should do it, and present: 应该这样做,并提出:
array(2) {
["W0000000391"]=>
float(155)
["W0000000396"]=>
float(170)
}
But, to match your required format more: 但是,要进一步匹配所需的格式,请执行以下操作:
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'];
}
But keys need to be unique, so you can leave them like this or run a sort()
on the resulting array to reset the array keys to the integer values 但是键必须是唯一的,因此您可以像这样保留它们或在结果数组上运行
sort()
以将数组键重置为整数值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.