How to fold a amount of items with the same date?

There is an array of this type

{
 "issuance": {
 "1": {
 "data": "01.20",
 quantity: 2
},
 "2": {
 "data": "01.20",
 quantity: 4
},
 "3": {
 "data": "04.20",
 quantity: 2
},
 "4": {
 "data": "04.20",
 quantity: 2
}
}


how to get the array like this (i.e. add up all quantity)

{
 "issuance": {
 "1": {
 "data": "01.20",
 quantity: 6
},
 "2": {
 "data": "04.20",
 quantity: 4
}
}
April 4th 20 at 13:11
2 answers
April 4th 20 at 13:13
Solution
<?php

$json = <<<JSON
{
 "issuance": {
 "1": {
 "data": "01.20",
 quantity: 2
},
 "2": {
 "data": "01.20",
 quantity: 4
},
 "3": {
 "data": "04.20",
 quantity: 2
},
 "4": {
 "data": "04.20",
 quantity: 2
}
}
}
JSON
;

$arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

$res = new \stdClass();
$res->issuance = array_values(
array_reduce(
$arr['issuance'],
 function ($res, $el) {
 $res[$el['data']]['data'] = $el['data'];
 $res[$el['data']]['quantity'] = isset($res[$el['data']]['quantity'])
 ? $res[$el['data']]['quantity'] + $el['quantity']
 : $el['quantity'];

 return $res;
},
[]
)
);

var_dump(json_encode($res, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT, 512));

sandbox.onlinephpfunctions.com/code/c5986c6fd8244a...

* JSON_THROW_ON_ERROR — this flag appeared only in 7.3, if the version is less to clean up
April 4th 20 at 13:15
too much.
As an example can show - Irving_Mante commented on April 4th 20 at 13:18
@Irving_Mante, foreach -> if data equals -> ++ - Rebeca10 commented on April 4th 20 at 13:21
@Irving_Mante, there you hinted in the comments that you can get directly from the source, if the database pull if from the API, too - Baby commented on April 4th 20 at 13:24

Find more questions by tags PHP