php 如何对子数组元素求和并按子数组值分组?[重复]

irlmq6kh  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(106)

此问题已在此处有答案

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",
]
]
j8ag8udp

j8ag8udp1#

你只需要使用foreach一次,并且在使用前你需要定义$total_balance数组中的键。请看下面的代码

$total_balances = array();
foreach ($balances as $balance) {
    if( !isset( $total_balances[$balance['Portfolio']] )) {
        $total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0); 
    }
    $total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
    $total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}

相关问题