[英]How to skip first item in a foreach loop in Laravel?
我正在尝试使用基于存储在数据库中的内容的内容填充我的网页。 但是,我想跳过第一项; 我想从第二个项目开始循环。
我怎样才能做到这一点?
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
从 Laravel 5.4 开始,每当你在刀片文件中使用foreach
或for
,你现在都可以访问$loop 变量。 $loop 变量提供了许多有用的属性和方法,其中一个在这里很有用,用于跳过第一次迭代。 请参阅下面的示例,这是实现与此处其他旧答案相同的结果的更简洁的方法:
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
试试这个:
@foreach($aboutcontent as $key => $about)
@if($key > 0){
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif;
@endforeach
假设$aboutcontents
是数字数组,只需使用老式的for
循环而不是新的foreach
// Notice you start at 1 and your first
// elem is 0 so... ta da... skipped
@for ($i = 1; $i < count($aboutcontents); $i++){
$about = $aboutcontents[$i]; //This is the object
//now use $about as you would
}
注意:我没有使用过 Larvel 或刀片,但根据文档,这应该是可行的
如果您想在刀片中执行此操作,则需要某种计数器:
<?php $count = 0;?>
@foreach
@if($count>1)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif
$count++
@endforeach
编辑:
我更喜欢 Mark Baker 在评论中提供的答案
@foreach(array_slice($aboutcontent, 1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
或者,您可以在迭代之前从数组中删除第一个元素:
@php
array_shift($aboutcontent);
@endphp
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
优点是您不需要任何条件来验证您不是第一次迭代中的那个。 缺点是您可能需要同一视图中的第一个元素,但我们从您的示例中不知道。
注意在将数据传递给视图之前从数组中删除第一个元素可能更有意义。
参考:
有两种方法可以做到这一点:1-如果您的 $key 是数字,您可以使用:
@foreach($aboutcontent as $key => $about)
@if($key == 0)
@continue
@endif
code
@endforeach
2- 如果 $key 不是数字,则使用 @loop->first 作为条件
尝试这个
@foreach($aboutcontent->slice(1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.