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

Laravel Collection如何按sex字段不同值分别求和total字段

实现方案

你可以先使用Laravel集合的groupBy()方法按sex字段分组,再遍历每个分组单独求和即可,核心代码如下:

// 按sex分组后分别统计total总和
$sexTotal = $output->groupBy('sex')
    ->map(function ($group) {
        return $group->sum('total');
    });

// PHP 7.4及以上版本可以用箭头函数简化写法
$sexTotal = $output->groupBy('sex')
    ->map(fn($group) => $group->sum('total'));

执行结果说明

返回的$sexTotal是一个Illuminate\Support\Collection对象,键为sex的取值(1、2),值为对应分组的total总和,你提供的示例数据对应的返回结果结构如下:

Illuminate\Support\Collection {
  #items: array:2 [
    1 => 2147275849.770301 // 1037931027.8459 + 1103340160.4262 + 6004661.498201的计算结果
    2 => 1091237622.0488
  ]
}

如果需要转成普通数组,在链式调用最后追加->toArray()即可。

可选:提前过滤sex取值

如果你的集合中存在sex不为1、2的条目,需要提前过滤再统计,可以加上whereIn筛选:

$sexTotal = $output->whereIn('sex', [1,2])
    ->groupBy('sex')
    ->map(fn($group) => $group->sum('total'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:06:03