My Array
Array (
[1] => Array (
[username] => Test
[description] => Hello
[country] => USA
[menu] => Array (
[1] => Array (
[id] => 1
[level] => 1
[level_2_categories] => Array (
[level] => 2
[services] => Array (
[1] ...
[2] ...
[3] ... )
[2] => Array (
[id] => 2
[level] => 1
[level_2_categories] => Array (
[level] => 2
[services] => Array (
)
[3] => Array (
[id] => 3
[level] => 1
[level_2_categories] => Array (
[level] => 2
[services] => Array (
[1] ...
[2] ...
[3] ... )
)
)
Laravel
@foreach ($professional->menu as $index => $menu)
@foreach ($menu->level_2_categories as $category)
@if (count($category->services)>0)
<li>
<a href="#{{ $menu->id}}" data-toggle="tab">
<div class="category-box">
<span class="arrow">{{ $menu->id }}</span>
</div>
</a>
</li>
@endif
@endforeach
@endforeach
I am trying to print [id] for each of the menu arrays except those with no arrays in [services] (the second array for menu). Tried the code above but Laravel outputs the menu ids by multiple times due to the nested @foreach. Would appreciate any help thanks!
martincarlin87 :
Updated answer, if you are using a Laravel version > 5.3, you could use the built in $loop variable:\n\n@foreach ($professional->menu as $index => $menu)\n @foreach ($menu->level_2_categories as $category)\n @if (count($category->services) > 0 && $loop->index == 0)\n <li>\n <a href=\"#{{ $menu->id}}\" data-toggle=\"tab\">\n <div class=\"category-box\">\n <span class=\"arrow\">{{ $menu->id }}</span>\n </div>\n </a>\n </li>\n @endif\n @endforeach\n@endforeach\n\n\nhttps://laravel.com/docs/5.5/blade#loops",
2017-12-12T11:04:21