我的数组
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
我正在尝试为每个菜单数组打印[id],除了[services]中没有数组的菜单(菜单的第二个数组)。尝试上面的代码,但由于嵌套的@foreach,Laravel多次输出菜单ID。非常感谢任何帮助谢谢!
答案 0 :(得分:-1)
尝试维护count
,如下面的代码所示:
@foreach ($professional->menu as $index => $menu)
<?php $count=0;?> // change over here
@foreach ($menu->level_2_categories as $category)
@if (count($category->services) > 0 && $count==0) // change over here
<?php $count++; ?> // change over here
<li>
<a href="#{{ $menu->id}}" data-toggle="tab">
<div class="category-box">
<span class="arrow">{{ $menu->id }}</span>
</div>
</a>
</li>
@endif
@endforeach
@endforeach
答案 1 :(得分:-1)
如果您使用的是Laravel版本&gt;更新的答案5.3,您可以使用内置的$loop
变量:
@foreach ($professional->menu as $index => $menu)
@foreach ($menu->level_2_categories as $category)
@if (count($category->services) > 0 && $loop->index == 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