You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP嵌套关联数组按分组对同键名数值求和实现方法

PHP 按顶级分组累加子数组同键值的实现方案

原有代码问题

  • 初始将$sum定义为整数0,后续却作为数组操作,类型逻辑矛盾
  • 仅遍历了顶级分组层,未深入遍历每个分组下的子数组逐键累加
  • 直接使用数组加法运算符无法实现同键值求和的逻辑,还会触发类型错误

可直接运行的正确代码

<?php
// 待处理的原始数组
$ar = array(
    'Services' => array(
        array('9' => '0','10' => '0','11' => '0','12' => '0','13' => '0','14' => '0','15' => '600'),
    ),
    'Financial' => array(
        array('9' => 0,'10' => 0,'11' => 0,'12' => 0,'13' => 0,'14' => 0,'15' => 500),
        array('9' => 0,'10' => 0,'11' => 0,'12' => 0,'13' => 0,'14' => 0,'15' => 200),
        array('9' => 0,'10' => 0,'11' => 0,'12' => 0,'13' => 0,'14' => 0,'15' => 300),
    ),
    'DFD' => array(
        array('9' => 0,'10' => 0,'11' => 0,'12' => 0,'13' => 0,'14' => 0,'15' => 1000),
        array('9' => 0,'10' => 0,'11' => 0,'12' => 0,'13' => 0,'14' => 0,'15' => 100)
    )
);

$result = [];
// 指定需要累加的键范围9~15
$statKeys = range(9, 15);

foreach ($ar as $groupKey => $itemList) {
    // 初始化当前分组所有统计键的初始值为0
    $result[$groupKey] = array_fill_keys($statKeys, 0);
    // 遍历分组下所有子项逐键累加
    foreach ($itemList as $item) {
        foreach ($statKeys as $numKey) {
            // 强制转整型,兼容原数组中字符串格式的数字值
            $result[$groupKey][$numKey] += (int)$item[$numKey];
        }
    }
}

// 输出结果验证
print_r($result);

运行结果

执行代码后输出的结果完全匹配需求:

Array
(
    [Services] => Array
        (
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
            [13] => 0
            [14] => 0
            [15] => 600
        )

    [Financial] => Array
        (
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
            [13] => 0
            [14] => 0
            [15] => 1000
        )

    [DFD] => Array
        (
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
            [13] => 0
            [14] => 0
            [15] => 1100
        )
)

内容的提问来源于stack exchange,提问作者Poobalan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 23:48:49