You need to enable JavaScript to run this app. PHP如何按service和type双字段分组数组并累加taskCount、usageTime
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何按service和type双字段分组数组并累加taskCount、usageTime

问题原因

你当前的代码存在三处问题:

  1. 仅使用service作为分组键,没有将type加入分组维度,导致同一服务下不同类型的条目被错误合并
  2. 求和的时长字段名写错,原数组存储时长的字段是usageTime,不是totalDuration
  3. array_reduce没有传入初始空数组作为第三个参数,可能出现类型错误

修正代码

如果你的数组元素是关联数组,使用如下代码:

$myArr = array_reduce($myArr, function($carry, $item) {
    // 拼接service和type作为唯一分组标识
    $groupKey = $item['service'] . '|' . $item['type'];
    if (!isset($carry[$groupKey])) {
        $carry[$groupKey] = $item;
    } else {
        $carry[$groupKey]['taskCount'] += $item['taskCount'];
        $carry[$groupKey]['usageTime'] += $item['usageTime'];
    }
    return $carry;
}, []);

// 重置为索引数组
$myArr = array_values($myArr);

如果你的数组元素是对象,将数组访问符替换为对象访问符即可:

$myArr = array_reduce($myArr, function($carry, $item) {
    $groupKey = $item->service . '|' . $item->type;
    if (!isset($carry[$groupKey])) {
        $carry[$groupKey] = $item;
    } else {
        $carry[$groupKey]->taskCount += $item->taskCount;
        $carry[$groupKey]->usageTime += $item->usageTime;
    }
    return $carry;
}, []);

$myArr = array_values($myArr);

修改后即可按照service和type两个字段分组求和,得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 12:15:03