如何用Laravel Collection Chunk方法调整最后两组元素至各2条?
问题:调整Laravel Collection分组,使最后两组各含2条记录
我正在使用Laravel 9.x的Collection,通过chunk(3)方法将数据按每组3条拆分。当前最后一组仅包含1条记录,需要将前一组的最后1条记录移至最后一组,让最后两组各有2条记录。
当前分组结果:最后一组仅1条数据,前一组为3条数据
预期分组结果:最后两组各包含2条数据
当前视图代码:
<table> <thead> <tr> <th>#</th> <th>Hour</th> <th>Player</th> </tr> </thead> <tbody> @foreach ($players->chunk(3) as $player) @foreach ($player->sortBy('index') as $detail) <tr> <td class="font-weight-bold">{{ $loop->parent->iteration }}</td> <td> {{ $detail->hour }} </td> <td class="text-left"> {{ $detail->name }} </td> </tr> @endforeach @endforeach </tbody> </table>
解决方案
方法一:直接处理Laravel Collection
先对数据统一排序(避免在视图中重复排序),再判断最后一组的长度,手动调整分组:
$chunkSize = 3; // 先按index排序,统一处理 $players = $players->sortBy('index'); $chunks = $players->chunk($chunkSize); // 当最后一组只有1条,且分组数大于1时调整 if ($chunks->count() > 1 && $chunks->last()->count() === 1) { // 获取倒数第二组 $secondLastChunk = $chunks->get($chunks->count() - 2); // 取出该组最后一条数据 $movedItem = $secondLastChunk->pop(); // 将数据添加到最后一组 $chunks->put($chunks->count() - 1, $chunks->last()->push($movedItem)); }
修改视图,直接使用处理好的$chunks(已提前排序,无需在视图中再次排序):
<table> <thead> <tr> <th>#</th> <th>Hour</th> <th>Player</th> </tr> </thead> <tbody> @foreach ($chunks as $playerGroup) @foreach ($playerGroup as $detail) <tr> <td class="font-weight-bold">{{ $loop->parent->iteration }}</td> <td>{{ $detail->hour }}</td> <td class="text-left">{{ $detail->name }}</td> </tr> @endforeach @endforeach </tbody> </table>
方法二:使用PHP数组函数处理
如果更习惯原生PHP数组操作,可以先转成数组再调整:
$chunkSize = 3; // 排序后转数组 $playerArray = $players->sortBy('index')->toArray(); $chunks = array_chunk($playerArray, $chunkSize); // 判断并调整最后两组 if (count($chunks) > 1 && count(end($chunks)) === 1) { // 从倒数第二组移最后一条到最后一组 $chunks[count($chunks)-1][] = array_pop($chunks[count($chunks)-2]); // 转回Collection(如果需要保持Collection类型) $chunks = collect($chunks)->map(fn($chunk) => collect($chunk)); }
视图代码与方法一的修改版一致。
内容的提问来源于stack exchange,提问作者Cristian Bustos
相关产品推荐
相关产品推荐

