
本文介绍如何在 laravel 中使用集合(Collection)高效地按 year 字段对多维数组进行分组,并对指定数值字段(如 total_policies_financed 和 total_amount_financed)执行求和,同时统计每组记录数。
本文介绍如何在 laravel 中使用集合(collection)高效地按 `year` 字段对多维数组进行分组,并对指定数值字段(如 `total_policies_financed` 和 `total_amount_financed`)执行求和,同时统计每组记录数。
在 Laravel 开发中,常需对原始数据数组按某一维度(如年份)进行分组聚合,例如统计每年的保单总数、融资总额等指标。原生 PHP 循环虽可实现,但代码冗长且易出错;而 Laravel 的 Collection 提供了声明式、链式调用的优雅解决方案。
核心思路是三步操作:
以下为完整可运行示例:
// 假设 $data 是你的原始数组 $data = [ ['year' => 2022, 'total_policies_financed' => 1, 'total_amount_financed' => 280.0], ['year' => 2022, 'total_policies_financed' => 2, 'total_amount_financed' => 5190.0], ['year' => 2021, 'total_policies_financed' => 2, 'total_amount_financed' => 5190.0], ]; $result = collect($data) ->groupBy('year') ->map(function ($items, $year) { return [ 'year' => (int) $year, 'total_count' => $items->count(), 'total_policies_financed' => $items->sum('total_policies_financed'), 'total_amount_financed' => round($items->sum('total_amount_financed'), 2), ]; }) ->values() ->toArray(); print_r($result);
✅ 输出结果将严格匹配预期格式:
[ [ 'year' => 2022, 'total_count' => 2, 'total_policies_financed' => 3, 'total_amount_financed' => 5470.0 ], [ 'year' => 2021, 'total_count' => 1, 'total_policies_financed' => 2, 'total_amount_financed' => 5190.0 ] ]
⚠️ 注意事项:
- groupBy() 的键值(如 ‘year’)必须存在于所有子数组中,否则会触发 undefined index 警告;建议提前校验或使用 optional() 辅助;
- sum() 方法自动忽略非数值项(返回 0),但若字段可能为 NULL 或字符串,建议先用 Filter() 清洗或 map() 转换类型;
- 若需保持年份升序/降序,可在 map() 后添加 ->sortBy(‘year’) 或 ->sortByDesc(‘year’);
- ->values() 用于重置键名,确保输出为连续数字索引数组(避免保留年份作为键导致 json 序列化异常)。
该方案简洁、可读性强,充分利用 Laravel 集合的函数式能力,适用于 Eloquent 查询结果、API 响应处理或后台报表生成等场景。