Search code examples
phplaravellaravel-bladenested-loops

Laravel getting last items from 2nd Level of nested array


I am working with laravel framework and I have a nested array in which to display a subset of results. For example, on the array below I display multi task per year.

Array
(
  [0] => years_tasks_section_grid
    (
      [0] => 2022
      [1] => tasks_grid
        (
          [0] => Task1 2022
          [1] => Task2 2022
          [2] => Task3 2022
          [3] => Task4 2022
          [4] => Task5 2022
          [5] => Task6 2022
        )
    )

  [1] => years_tasks_section_grid
    (
      [0] => 2021
      [1] => tasks_grid
        (
          [0] => Task1 2021
          [1] => Task2 2021
          [2] => Task3 2021
        )
    )
)

The problem I want to display the last 3 tasks from the 2nd level of nested array. Basically, based on my example I try to get this (only tasks of 2022):

[0] => Task1 2022
[1] => Task2 2022
[2] => Task3 2022

But I am getting this (Basically, I am getting both 3 last tasks 2022 and 2021 and probably I will have other tasks of the future years):

[0] => Task1 2022
[1] => Task2 2022
[2] => Task3 2022

[0] => Task1 2021
[1] => Task2 2021
[2] => Task3 2021

This is my code in Laravel blade (I used array_slice but is not working because I have the result as above):

@foreach($sections['years_tasks_section_grid'] as $year)
   @foreach(array_slice($year['tasks_grid'], 0, 5) as $task)
       <div class="col-md-4 col-xl-2 d-flex align-items-center justify-content-center justify-content-md-start mb-7 mb-xl-0 px-0">          
            // Other code
       </div>
   @endforeach
@endforeach

Any ideas?


Solution

  • You could use a $counter, initialized at 0 and wrap it around your div. First, let's create the variable:

    @php
    $counter = 1
    @endphp
    

    and now, let's wrap it around your div:

    @foreach($sections['years_tasks_section_grid'] as $year)
       @foreach(array_slice($year['tasks_grid'], 0, 5) as $task)
           @if ($counter++ < 3)
           <div class="col-md-4 col-xl-2 d-flex align-items-center justify-content-center justify-content-md-start mb-7 mb-xl-0 px-0">          
                // Other code
           </div>
           @endif
       @endforeach
    @endforeach