php - 如何在 laravel 刀片中拆分 foreach 循环
问题描述
在刀片中使用时,有没有办法拆分雄辩搜索的结果?我问,因为我有一个引导轮播,它是 2 张幻灯片,每张幻灯片分成 3 列。我想要它,以便每张幻灯片都填写以下搜索的结果:
$alsoBought = Game::where('category_id', $showGames['category_id'])->paginate(6);
如您所见,它带回了 6 个结果。有没有办法拆分它,以便每张幻灯片上有 3 个结果?这是我的幻灯片代码:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div class="row">
@foreach($alsoBought->take(3) as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
<div class="carousel-item">
<div class="row">
@foreach($alsoBought as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
</div>
</div>
解决方案
您可以chunk()
在集合上使用,而不是take()
在每个块中传递您想要的项目数量
@foreach($alsoBought->chunk(3) as $three)
<div class="carousel-item @if ($loop->first) active @endif">
<div class="row">
@foreach($three as $bought)
<div class="col-4"><img class="w-100" src="{{ $bought['image'] }}" alt="First slide"></div>
@endforeach
</div>
</div>
@endforeach
从文档
该chunk
方法将集合分解为多个给定大小的较小集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
推荐阅读
- python - 使用python循环调用多个SQL数据库
- node.js - 尝试使用 map() 解决 API 的 Promise
- mongodb - 使用 MongoDB 字段作为另一个值的键引用
- flutter - 为什么我无法在 FLutter 中捕获 Grpc 错误?
- angular - 无法从可观察对象数组中返回过滤后的可观察对象
- aws-lambda - AWS Lambda 连接到 Docker 中的本地 Postgres
- c++ - 打印同一个数组,不同的功能是不同的,为什么?
- html - 带有下载属性的标签在 iphone 中不起作用?
- java - 如何改进对日志文件的数据处理
- asp.net-mvc - ASP.NET MVC 中的会话超时问题?