首页 > 解决方案 > 如何在 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>

标签: phplaraveleloquent

解决方案


您可以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]]

推荐阅读