此问题已在此处有答案:
How to GROUP BY and SUM PHP Array? [duplicate](2个答案)
How to group by and sum a multi-dimensional array?(2个答案)
11个月前关闭。
我想对子数组值求和并按子数组值分组,但出现错误:'未定义索引:EEReg'.
数组如下。
当前编码为;
$total_balances = array();
foreach ($balances as $balance) {
foreach ($balance as $key => $value) {
if ($key == 'MemberNumber' || $key == 'Portfolio') {
continue;
} else {
$total_balances[$balance['Portfolio']][$key] += $value;
}
}
}
我期望结果是;
$total_balances = [
"Aggressive" => [
"EEReg" => "Sum of EEReg where Portfolio is Aggressive",
"ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
"Moderate" => [
"EEReg" => "Sum of EEReg where Portfolio is Moderate",
"ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]
1条答案
按热度按时间j8ag8udp1#
你只需要使用foreach一次,并且在使用前你需要定义$total_balance数组中的键。请看下面的代码