如何在PHP / Blade中为Laravel使用Foreach循环?

时间:2017-11-14 17:07:34

标签: php laravel foreach blade

这是一个简单的问题: 有没有办法用foreach循环或类似的东西来优化这段代码?

@if(isset($tags[0]))
    <span class="label label-primary">{{ $tags[0] }}</span>
@endif
@if(isset($tags[1]))
    <span class="label label-primary">{{ $tags[1] }}</span>
@endif
@if(isset($tags[2]))
    <span class="label label-primary">{{ $tags[2] }}</span>
@endif
@if(isset($tags[3]))
    <span class="label label-primary">{{ $tags[3] }}</span>
@endif
@if(isset($tags[4]))
    <span class="label label-primary">{{ $tags[4] }}</span>
@endif
@if(isset($tags[5]))
    <span class="label label-primary">{{ $tags[5] }}</span>
@endif
@if(isset($tags[6]))
    <span class="label label-primary">{{ $tags[6] }}</span>
@endif
@if(isset($tags[7]))
    <span class="label label-primary">{{ $tags[7] }}</span>
@endif
@if(isset($tags[8]))
    <span class="label label-primary">{{ $tags[8] }}</span>
@endif
@if(isset($tags[9]))
    <span class="label label-primary">{{ $tags[9] }}</span>
@endif           

谢谢你,祝你今晚愉快!

4 个答案:

答案 0 :(得分:12)

你可以这样做:

@foreach ($tags as $tag)
    <span class="label label-primary">{{ $tag }}</span>
@endforeach

答案 1 :(得分:4)

您可以使用@foreach循环(如其他答案所示)或@for循环。对控制结构使用blade语法(前面有@符号)

@for($i = 0; $i <= 9; $i++)
@if(isset($tags[$i]))
<span class="label label-primary">{{ $tags[$i] }}</span>
@endif
@endfor

答案 2 :(得分:4)

根据documentation,您可以执行@for循环。

@for ($i = 0; $i < 10; $i++)
    @if(isset($tags[$i]))
         <span class="label label-primary">{{ $tags[$i] }}</span>
    @endif
@endfor

答案 3 :(得分:0)

@foreach ($tags as $data) 
<span class="label label-primary">{{$data->property }}</span> 
@endforeach

您也可以在刀片中使用for else,只需查看laravel文档即可 https://laravel.com/docs/5.5/blade