【问题标题】:How to split a foreach loop in laravel blade如何在 laravel 刀片中拆分 foreach 循环
【发布时间】:2021-01-26 17:27:19
【问题描述】:

在刀片中使用雄辩搜索的结果时,有没有办法拆分它?我问,因为我有一个引导轮播,它是 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>

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以在集合上使用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
    

    来自the docs

    chunk 方法将集合分成多个给定大小的较小集合:

    $collection = collect([1, 2, 3, 4, 5, 6, 7]);
    
    $chunks = $collection->chunk(4);
    
    $chunks->toArray();
    
    // [[1, 2, 3, 4], [5, 6, 7]]
    

    【讨论】:

      【解决方案2】:

      假设您有 10 条记录要在 Blade 中显示,但您需要分 2 部分显示它们,每部分 5 条记录。在@foreach 循环中使用chunk 有一个非常好的技巧。

      试试这个。

      <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
                  <div class="carousel-inner">
                  @foreach($alsoBought->chunk(3) as $bought)
                      <div class="carousel-item @if($loop->first) {{ 'active' }} @endif">
                          <div class="row">
      
                              @foreach($bought as $item)
                                  <div class="col-4"><img class="w-100" src="{{ $item['image'] }}" alt="First slide"></div>
                              @endforeach 
      
                          </div>
                      </div>
                  @endforeach
      
                  </div>
              </div>
      

      【讨论】:

      • 好的,删除我的评论。
      • 没关系,我相信你。我不需要证据。
      猜你喜欢
      • 2018-04-04
      • 2017-11-13
      • 2016-06-29
      • 2017-12-24
      • 2017-05-29
      • 1970-01-01
      • 2021-02-11
      • 2017-09-26
      • 2019-10-11
      相关资源
      最近更新 更多