
本文介绍如何在 Laravel 中使用集合(Collection)高效地按 year 字段对多维数组进行分组,并对指定数值字段(如 total_policies_financed 和 total_amount_financed)执行求和,同时统计每组记录数。
本文介绍如何在 laravel 中使用集合(collection)高效地按 `year` 字段对多维数组进行分组,并对指定数值字段(如 `total_policies_financed` 和 `total_amount_financed`)执行求和,同时统计每组记录数。
在 Laravel 开发中,常需对原始数据数组按某一维度(如年份)进行分组聚合,例如统计每年的保单总数、融资总额等指标。原生 PHP 循环虽可实现,但代码冗长且易出错;而 Laravel 的 Collection 提供了声明式、链式调用的优雅解决方案。
核心思路是三步操作:
- 将原始数组转为 Illuminate\Support\Collection 实例;
- 使用 groupBy('year') 按年份分组;
- 通过 map() 对每组数据计算聚合值,并重构结构。
以下为完整可运行示例:
// 假设 $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 响应处理或后台报表生成等场景。










