如何使用PHP在每三个元素之后显示一个项



我试图在每三个{{ $image->title }}之后显示一个项目,
但是我使用的方法在加载页面时产生了一点延迟,即当我删除<div class='extra'>时,减少了200ms。
下面有没有最好的替代方法?

@foreach( $images as $index =>$image)  
<div>
{{ $image->title }}
</div>
@if( count($images) > 0 && $index != 0 && ($index % 3) == 0 )
<div class="extra">
Item to show after three Image Titles
</div>
@endif    
@endforeach

Laravel有自己的Blade $loop变量,旨在帮助您完成此操作,请查看这里的文档https://laravel.com/docs/8.x/blade#loops

在你的情况下,像这样的东西更有意义

@foreach( $images as $index =>$image)  
<div>
{{ $image->title }}
</div>
@if( $loop->iteration % 3) // this can be $loop->index but im not sure what you need
<div class="extra">
Item to show after three Image Titles
</div>
@endif    
@endforeach

最新更新