Laravel集合分组数据处理:移除外层数组并修正结果
问题:移除Laravel集合分组后的双层数组结构
我需要先对获取的数据进行计算处理,再按id分组,但当前输出带有双层数组结构,希望移除外层数组,得到符合预期的结果。
当前输出数据
"data": [ [ { "id": 2, "runtime_batch": 24528, "smallstoptime_batch": 250, "downtime_batch": 200 }, { "id": 2, "runtime_batch": 2074, "smallstoptime_batch": 0, "downtime_batch": 1 } ], [ { "id": 3, "runtime_batch": 185, "smallstoptime_batch": 252, "downtime_batch": 1409 }, { "id": 3, "runtime_batch": 2127, "smallstoptime_batch": 377, "downtime_batch": 22452 } ] ]
当前使用的代码
$linedata = GetMyData::select('id', 'runtime_batch', 'smallstoptime_batch', 'downtime_batch', 'output', 'output_final')->get(); foreach($linedata as $ld) { $ld->runtime_batch = round(($ld->runtime_batch+$ld->smallstoptime_batch)/($ld->runtime_batch+$ld->smallstoptime_batch+$ld->downtime_batch)*100, 2); $ld->downtime_batch = round($ld->output/$ld->output_final*100, 2); $ld->smallstoptime_batch = round($ld->output_final/($ld->runtime_batch+$ld->smallstoptime_batch)*100, 2); } $groupingline = collect($linedata)->groupBy('id')->values()->all();
解决方案
1. 先修正数据计算的潜在问题
原代码中计算smallstoptime_batch时,使用了已经被修改过的runtime_batch值,会导致计算结果偏差。建议改用getOriginal()获取数据库原始值计算,同时用集合的map方法替代foreach,更符合Laravel写法:
$linedata = GetMyData::select('id', 'runtime_batch', 'smallstoptime_batch', 'downtime_batch', 'output', 'output_final') ->get() ->map(function ($ld) { // 计算总时长(用原始值) $totalTime = $ld->getOriginal('runtime_batch') + $ld->getOriginal('smallstoptime_batch') + $ld->getOriginal('downtime_batch'); // 计算runtime_batch $ld->runtime_batch = round(($ld->getOriginal('runtime_batch') + $ld->getOriginal('smallstoptime_batch')) / $totalTime * 100, 2); // 计算downtime_batch $ld->downtime_batch = round($ld->output / $ld->output_final * 100, 2); // 计算smallstoptime_batch(用原始值) $ld->smallstoptime_batch = round($ld->output_final / ($ld->getOriginal('runtime_batch') + $ld->getOriginal('smallstoptime_batch')) * 100, 2); return $ld; });
2. 移除双层数组结构的两种方式
方式一:将分组元素平铺为一维数组
如果需要把所有分组内的元素合并到一个单层数组中,使用flatten()方法:
$groupingline = $linedata->groupBy('id')->flatten()->all();
输出结果为:
"data": [ { "id": 2, "runtime_batch": 24528, "smallstoptime_batch": 250, "downtime_batch": 200 }, { "id": 2, "runtime_batch": 2074, "smallstoptime_batch": 0, "downtime_batch": 1 }, { "id": 3, "runtime_batch": 185, "smallstoptime_batch": 252, "downtime_batch": 1409 }, { "id": 3, "runtime_batch": 2127, "smallstoptime_batch": 377, "downtime_batch": 22452 } ]
方式二:保留分组结构但用id作为键
如果需要保留按id分组的逻辑,但不想用数字索引的外层数组,去掉values()方法即可,得到以id为键的关联数组:
$groupingline = $linedata->groupBy('id')->all();
输出结果为:
"data": { "2": [ { "id": 2, "runtime_batch": 24528, "smallstoptime_batch": 250, "downtime_batch": 200 }, { "id": 2, "runtime_batch": 2074, "smallstoptime_batch": 0, "downtime_batch": 1 } ], "3": [ { "id": 3, "runtime_batch": 185, "smallstoptime_batch": 252, "downtime_batch": 1409 }, { "id": 3, "runtime_batch": 2127, "smallstoptime_batch": 377, "downtime_batch": 22452 } ] }
内容的提问来源于stack exchange,提问作者Test Doang
相关产品推荐
相关产品推荐

