数组和组中的产品价格总和
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
[{
"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?
foreach($jsonDecoded as $item) {
$sortedData[$item['categorycode']] = array(
'Konto' => $item['categorycode'],
'Beløb' => $item['grosssalesprice']
);
}
我有这个JSON数组我解码成一个PHP数组,并想检查已售出多少 每个类别 p>
[{
“categorycode”:“W0000000391”,
“grosssalesprice”:“50.00”
},
{
“categorycode”: “W0000000396”,
“grosssalesprice”:“170.00”
},
{
“categorycode”:“W0000000391”,
“grosssalesprice”:“50.00”
},
{
“categorycode “:”W0000000391“,
”grosssalesprice“:”55.00“
}]
code> pre>
并希望获得 p>
{
“categorycode”:“W0000000391”,
“grosssalesprice”:“155.00”
},
{
“categorycode”:“W0000000396”,
“grosssalesprice”:“170.00 “
}
code> pre>
我试过,这给了我一个条目foreach元素,但是我如何追加这个数组中的每个项目? p>
foreach($ jsonDecoded as $ item){
$ sortedData [$ item ['categorycode']] = array(
'Konto'=> $ item [ 'categorycode'],
'Beløb'=> $ item ['grosssalesprice']
);
}
code> pre>
div>
$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