用这个:
$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;
}
我得到:
[
{
"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
}
]
但我需要$total
是101, 102, 103
的和。101, 102, 103
是动态的,因此这些键将不同。
我试图排除timeSummary,但似乎不起作用:
if (!$withTotal[$key]['timeSummary']) {
$total += array_sum($value);
}
4条答案
按热度按时间a11xaf1n1#
也许是这样的:
https://onlinephp.io/c/8cec8
yvgpqqbh2#
oug3syen3#
最后我取消了
timeSumary
的设置,设置了Total,然后再次设置了timeSummary
。xzv2uavs4#
不要将数据与元数据和聚合值保持在同一级别。将数据放在单独的列表属性中,如下所示:
检查online。