With this:
$obj1 = [
"101" => 18,
"102" => 15,
"103" => 23,
"timeSummary" => "2023-04-17 00:00:00"
];
$obj2 = [
"101" => 15,
"102" => 13,
"103" => 79,
"timeSummary" => "2023-04-18 00:00:00"
];
$obj3 = [
"101" => 50,
"102" => 50,
"103" => 62,
"timeSummary" => "2023-04-19 00:00:00"
];
$testArray = [$obj1, $obj2, $obj3];
// add Total
$withTotal = [];
$total = 0;
foreach ($testArray as $key => $value) {
array_push($withTotal, $value);
$total += array_sum($value);
$withTotal[$key]['total'] = $total;
}
I get:
[
{
"101": 18,
"102": 15,
"103": 23,
"timeSummary": "2023-04-17 00:00:00",
"total": 2079
},
{
"101": 15,
"102": 13,
"103": 79,
"timeSummary": "2023-04-18 00:00:00",
"total": 4209
},
{
"101": 50,
"102": 50,
"103": 62,
"timeSummary": "2023-04-19 00:00:00",
"total": 6394
}
]
but I need the $total
be the SUM of 101, 102, 103
. 101, 102, 103
are dynamic so these keys will be different.
I try to exclude timeSummary but it doesn’t seem to work:
if (!$withTotal[$key]['timeSummary']) {
$total += array_sum($value);
}
4
Answers
I ended up unsetting
timeSumary
setting the Total and then settingtimeSummary
again.Do not keep the data on the same level as the metadata and the aggregated values. Put the data in a separate list property, as below:
Check it online.
maybe something like this:
https://onlinephp.io/c/8cec8