PHP block array

0

How can I make this foreach show me blocks of 4 units?

 <div class="item active">
    @foreach($stores as $stores)
      <div class="item">
        <img src="/img/company/{{$stores->image}}">
      </div>
    @endforeach
 </div

When this carousel runs, it shows a single image at a time. What I want is that it shows a good 4 images for each pass without repeating the same image 4 times.

How can I achieve it?

    
asked by Cesar Augusto 17.08.2017 в 07:03
source

2 answers

1

My answer is similar to Luis Cabrero, but if $ stores is a Laravel Collection, you can use the chunk method to split it into 4 pieces.

This way, with two foreachs, you go through the groups of 4 and for each one the images.

So you'll have N item with up to 4 images each. The last group may have less depending on the size of your collection.

If they have to be groups of 4 you can use @if ($ stores-> count ()! = 4) to control this case.

<div class="item active">
    @php
        $gruposDe4 = $stores->chunk(4);
    @endphp
    @foreach($gruposDe4 as $stores)
      <div class="item">
      @foreach($stores as $stores)
          <img src="/img/company/{{$stores->image}}">
      @endforeach
      </div>
    @endforeach
 </div>
    
answered by 17.08.2017 / 13:41
source
0

Assuming that you have in the array $stores a number of elements module 4 the code would be the following. Of course, if not, the remaining% 4 would be out in the last iteration of the loop. You can later check that count($stores)%4 is 0, and if it is not, take the last elements of the array.

<div class="item active">
    @for($i = 0; $i < count($stores); $i+4)
      <div class="item">
        <img src="/img/company/{{$stores[$i]->image}}">
      </div>
      <div class="item">
        <img src="/img/company/{{$stores[$i+1]->image}}">
      </div>
      <div class="item">
        <img src="/img/company/{{$stores[$i+2]->image}}">
      </div>
      <div class="item">
        <img src="/img/company/{{$stores[$i+3]->image}}">
      </div>
    @endfor
    <!-- Si count($stores)%4 != 0 -->
    @if(count($stores)%4 != 0)
      <?php $mod = count(%stores)%4;?>
      @for($j = $mod; $j > 0; $j++)
        <div class="item">
          <img src="/img/company/{{$stores[count($stores) - $j]->image}}">
        </div>
      @endfor
    @endif
 </div>

I'm not very familiar with laravel but, well, I hope it helps, more or less the idea would be that. Greetings!

    
answered by 17.08.2017 в 09:33