php 在 Laravel Blade 中查找 foreach 循环的最后一次迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35976321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:38:42  来源:igfitidea点击:

Find last iteration of foreach loop in laravel blade

phplaravellaravel-5bladelaravel-blade

提问by user947668

In blade template i use last() method to find last iteration of foreach loop:

在刀片模板中,我使用 last() 方法来查找 foreach 循环的最后一次迭代:

@foreach ($colors as $k => $v)
   <option value={!! $v->id !!} {{ $colors->last()->id==$v->id ? 'selected':'' }} > {!! $v->name !!} </option>
@endforeach

Is it ok? Perhaps there is a Laravel-style way to do the same?

可以吗?也许有一种 Laravel 风格的方式来做同样的事情?

回答by Tom Kur

As for Laravel 5.3+, you can use the $loopvariable

至于 Laravel 5.3+,你可以使用$loop变量

$loop->last

@foreach ($colors as $k => $v)
     @if($loop->last)
         // at last loop, code here
     @endif
@endforeach

回答by Sebastian Sulinski

What you do is absolutely fine if you want to obtain instance of the last item in the collection.

如果您想获取集合中最后一项的实例,您所做的绝对没问题。

Additionally, in Laravel 5.3 you can use $loopvariable, which allows you to get boolean for last iteration $loop->lastor to obtain current iteration index $loop->iteration, total number of records $loop->countand a few more The Loop Variable

此外,在 Laravel 5.3 中,您可以使用$loop变量,它允许您获取上次迭代的布尔值$loop->last或获取当前迭代索引$loop->iteration、记录总数$loop->count和更多循环变量

@foreach ($posts as $post)

    {{ $post->title }} ({{ $loop->iteration }} of {{ $loop->count }})   

@endforeach

回答by cresjie

if $colorsis a Collection, $colors->last()and end($colors)both works

if$colors是 a Collection$colors->last()并且end($colors)两者都有效

回答by mohammad gitipasand

@foreach ($colors as $v)
    <option value={!! $v->id !!} {!!($v == end($colors)) ? 'selected="selected"' : '' !!} > {!! $v->name !!} </option>
@endforeach

or

或者

@foreach ($colors as $v)
    <option value={!! $v->id !!} {{($v == end($colors)) ? 'selected="selected"' : '' }} > {!! $v->name !!} </option>
@endforeach

回答by bim

Don't know if that last method is working but if not, try this:

不知道最后一种方法是否有效,但如果无效,请尝试以下方法:

@foreach ($colors as $v)
<option value={!! $v->id !!} @if($v == end($colors)) 'selected' @endif > {!! $v->name !!} </option>
@endforeach