0

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']
            );          
        }
Sonny Hansen
  • 620
  • 1
  • 5
  • 18
  • 4
    Here is something try coding for yourself: Loop through array, *add* value to the sum (stored in another array using the category code as a key). – Spoody Jul 25 '18 at 11:38
  • As what you have shown in your first JSON example is NOT VALID JSON, can you check it an make sure you have pasted all of the JSON String – RiggsFolly Jul 25 '18 at 11:40
  • Also look at `array_filter` and `array_reduce` – Zyigh Jul 25 '18 at 11:40

1 Answers1

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);

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

Jan Myszkier
  • 2,714
  • 1
  • 16
  • 23