How to get sum of distinct key -> value in php arrays

1732 views php
3

I have the following string thatI convert into a json array. All I am trying to do put together keys with the same value for id_number and sum the amount to each of these keys and print the resulting value outside the loop.

$response = '{
               "nhif":[
                  {
                     "id_number":"AA112233",
                     "amount":"5",
                     "date":"2018-09-14T20:18:50"
                  },
                  {
                     "id_number":"AA112233",
                     "amount":"5",
                     "date":"2018-09-14T19:59:14"
                  },
                  {
                     "id_number":"AA112233",
                     "amount":"5",
                     "date":"2018-09-14T09:07:34"
                  },
                  {
                     "id_number":"AA112233",
                     "amount":"5",
                     "date":"2018-09-14T09:04:27"
                  },
                  {
                     "id_number":"12345678",
                     "amount":"5",
                     "date":"2018-09-14T09:04:21"
                  }
               ]
            }';
$json_response = json_decode($response, true);

//Start NHIF
foreach ($json_response['nhif'] as $nhif) {
    echo ''.$nhif{"id_number"}.' '.$nhif{"amount"}.' '.$nhif{"date"}.'<br/>';
}
//END NHIF

My expected output is:

#id_number #amount
AA112233    20
12345678    5

Any workaround this?

answered question

I think this answer might help [PHP JSON Array - Group by the same value]( stackoverflow.com/a/27327976/5784900) . Basically you need to restructure your JSON array to be "grouped by" the same id_number. So once it is properly structured, you just need to iterate it and do your sum logic.

1 Answer

5

You can use array_reduce to sum the amount values by id_number:

$sums = array_reduce($json_response['nhif'], function ($c, $i) { 
     $c[$i['id_number']] = ($c[$i['id_number']] ?? 0) + $i['amount']; 
     return $c; 
}, array());
print_r($sums);

Output:

AA112233    20
12345678    5

posted this

Have an answer?

JD

Please login first before posting an answer.