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

分组Laravel Collection合并重复项并对指定字段求和方案咨询

你之前的写法问题在于groupBy(['type', 'size'])返回的是嵌套集合,直接单层map只能拿到第一层分组的sum结果,无法保留type、size字段,可参考以下两种实现:

方案1:适配现有嵌套分组逻辑

$data = collect($deliveryNote->line_items)
    ->groupBy(['type', 'size'])
    // 遍历第一层type分组,拍平结果
    ->flatMap(function ($sizeGroups, $type) {
        // 遍历第二层size分组
        return $sizeGroups->map(function ($items, $size) use ($type) {
            return [
                'type' => $type,
                'size' => $size,
                'amount' => $items->sum('amount')
            ];
        });
    })
    // 重置索引为连续数字
    ->values();

方案2:按组合键分组(逻辑更直观)

$data = collect($deliveryNote->line_items)
    // 用type+size的唯一组合作为分组键
    ->groupBy(fn($item) => $item['type'] . '|' . $item['size'])
    ->map(function ($group) {
        $first = $group->first();
        return [
            'type' => $first['type'],
            'size' => $first['size'],
            'amount' => $group->sum('amount')
        ];
    })
    ->values();

注意

如果你的line_items字段反序列化后是对象而非数组,将代码中的数组取值语法(如$item['type'])替换为对象属性语法(如$item->type)即可。两种方案最终输出的都是仅包含type、size、求和后amount的一维数组结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:02