如何使用Laravel Collection统计嵌套数组中相同值的出现次数
Laravel Collection 实现分月份统计状态出现频次
说明
原示例代码存在排版错位问题:February 实际应为和 January 同级的顶级数组键,并非嵌套在 January 的子数组中,以下实现基于修正排版后的正确业务结构编写。
实现代码
// 修正排版后的原始输入数据 $originalData = [ 'January' => [ ['status' => 'active'], ['status' => 'active'], ['status' => 'disable'], ['status' => 'active'], ], 'February' => [ ['status' => 'active'], ['status' => 'active'], ['status' => 'disable'], ['status' => 'disable'], ] ]; // 通过Collection链式方法完成统计 $statisticResult = collect($originalData) ->map(function ($monthRecordList) { return collect($monthRecordList) ->pluck('status') // 提取当前月份下所有条目的status值 ->countBy(); // 按status值统计出现次数,直接生成统计结构 }); // 转为纯数组格式即和你预期的输出结构完全匹配 $finalOutput = $statisticResult->toArray();
核心逻辑说明
- 不需要手动写多层
foreach做累加,Collection 原生提供的countBy()方法天然适配值频次统计的场景 - 最终输出的结果结构为:
[ 'January' => ['active' => 3, 'disable' => 1], 'February' => ['active' => 2, 'disable' => 2] ] - 如果需要兼容空数据场景,比如某月份没有任何记录时自动补全
active/disable的默认计数为0,可以在countBy()之后链式调用union(['active' => 0, 'disable' => 0])实现,不会影响已有统计值。
内容的提问来源于stack exchange,提问作者Panji Setya Nur Prawira
相关产品推荐
相关产品推荐

