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

PHP多维数组按discipline_name分组求crypt_count之和的技术问询

合并多维数组中相同discipline_name的crypt_count求和

这里有个简单高效的PHP实现方案,刚好能解决你的需求:

实现代码

// 假设你的原数组是这个变量
$disciplines = [
    ['discipline_name' => 'Fortitude', 'library_count' => 0, 'crypt_count' => 3],
    ['discipline_name' => 'Fortitude', 'library_count' => 0, 'crypt_count' => 1],
    ['discipline_name' => 'Obtenebration', 'library_count' => 0, 'crypt_count' => 3],
    ['discipline_name' => 'Obtenebration', 'library_count' => 0, 'crypt_count' => 2],
    ['discipline_name' => 'Dementation', 'library_count' => 1, 'crypt_count' => 0],
    ['discipline_name' => 'Obfuscate', 'library_count' => 0, 'crypt_count' => 2],
    ['discipline_name' => 'Fortitude', 'library_count' => 0, 'crypt_count' => 3],
    ['discipline_name' => 'Necromancy', 'library_count' => 0, 'crypt_count' => 1],
    ['discipline_name' => 'Necromancy', 'library_count' => 0, 'crypt_count' => 1],
    ['discipline_name' => 'Celerity', 'library_count' => 0, 'crypt_count' => 1],
    ['discipline_name' => 'Redemption', 'library_count' => 1, 'crypt_count' => 0],
    ['discipline_name' => 'Dominate', 'library_count' => 1, 'crypt_count' => 0],
    ['discipline_name' => 'Dominate', 'library_count' => 6, 'crypt_count' => 0],
    ['discipline_name' => 'Dominate', 'library_count' => 1, 'crypt_count' => 0],
    ['discipline_name' => 'Obtenebration', 'library_count' => 4, 'crypt_count' => 0],
    // 其他省略的元素...
];

// 初始化结果数组
$result = [];

foreach ($disciplines as $item) {
    $disciplineName = $item['discipline_name'];
    
    // 检查当前学科是否已存在于结果数组中
    if (isset($result[$disciplineName])) {
        // 累加crypt_count
        $result[$disciplineName]['crypt_count'] += $item['crypt_count'];
        
        // 如果你也需要对library_count求和,取消下面这行注释即可
        // $result[$disciplineName]['library_count'] += $item['library_count'];
    } else {
        // 首次出现该学科,直接存入结果数组
        $result[$disciplineName] = $item;
    }
}

// 可选:将关联数组转为索引数组(和原数组结构一致)
$result = array_values($result);

// 输出结果(调试用)
print_r($result);

代码说明

  • 我们用discipline_name作为结果数组的键,这样可以O(1)时间复杂度判断某个学科是否已经被处理,比嵌套循环效率高很多。
  • 遍历原数组时,若学科已存在,就累加crypt_count;若不存在,则直接把当前条目加入结果数组。
  • 最后用array_values()可以把结果转成和原数组一样的数字索引结构,如果你不需要这一步,直接用$result关联数组也可以。

处理后的结果示例

运行上面的代码后,你会得到合并后的数组,比如:

Array
(
    [0] => Array
        (
            [discipline_name] => Fortitude
            [library_count] => 0
            [crypt_count] => 7
        )

    [1] => Array
        (
            [discipline_name] => Obtenebration
            [library_count] => 0
            [crypt_count] => 5
        )

    [2] => Array
        (
            [discipline_name] => Dementation
            [library_count] => 1
            [crypt_count] => 0
        )

    // 其他条目省略...
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:51:32