Skip to content
Advertisement

Laravel – Collections. How to separate array into 2 groups

I have created 2 collections(arrays) which each contain an array of 5 items/events.

$events = Appget_event_data( $args )
$collection = collect($events['events']);
$event_chunks = $collection->chunk(5);
$event_chunks->toArray();

@foreach ($event_chunks as $chunk)

Output of the above:

object(IlluminateSupportCollection)[27632]
protected 'items' => 
  array (size=2)
    0 => 
      object(IlluminateSupportCollection)[27630]
        protected 'items' => 
          array (size=5)
            ...
    1 => 
      object(IlluminateSupportCollection)[27631]
        protected 'items' => 
          array (size=5)
            ...

In my next loop, it simply goes through every item of the array 1 by 1. I need to split the 5 items into a further 2 groups:
group of 2
group of 3
so I can wrap a div around each group.

Current loop:

@foreach ($chunk as $key => $event)
    <div class="item">
       {{ $event['title'] }}
    </div>
@endforeach

What I need:

<div class="item-group">
    [item1, item2]
</div>

<div class="item-group">
[item3, item4, item5]
</div>

Full code:

{{--  Get all events  --}}
@if( $events = Appget_event_data( $args ) )

  @php
    $collection = collect($events['events']);
    $event_chunks = $collection->chunk(5);
    $event_chunks->toArray();
  @endphp

  @foreach ($event_chunks as $chunk)

    <div class="{{ $block }}__flex-grid">

      @foreach ($chunk as $key => $event)
        <div class="item">
          {{ $event['title'] }}
        </div>
      @endforeach

    </div>

  @endforeach

@endif

Advertisement

Answer

Assuming that you will allways have 5 items, a solution could be:

<div class="item-group">
@foreach (array_slice($chunk->toArray(),0,2) as $key => $event)
    <div class="item">
      {{ $event['title'] }}
    </div>
@endforeach
</div>
<div class="item-group">
@foreach (array_slice($chunk->toArray(),2) as $key => $event)
    <div class="item">
      {{ $event['title'] }}
    </div>
@endforeach
</div>

Or if want to avoid code duplication:

@php $chunk = [array_slice($chunk->toArray(),0,2), array_slice($chunk,2)];

@foreach ($chunk as $group)
     <div class="item-group">
     @foreach ($group as $key => $event)
         <div class="item">
             {{ $event['title'] }}
         </div>
    @endforeach
    </div>
@endforeach

If you don’t know or not sure that you have 5, you may need to change the logic of the chunks/slice.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement