在foreach循環中可能有5或6個值,但我需要打印假設前5或6個值。我該怎麼做?如何在foreach循環中只打印4個值?
<div class="tag-area">
@foreach(explode(',',$product->tags) as $tag)
<span>{{$tag}}</span>
@endforeach
</div>
在foreach循環中可能有5或6個值,但我需要打印假設前5或6個值。我該怎麼做?如何在foreach循環中只打印4個值?
<div class="tag-area">
@foreach(explode(',',$product->tags) as $tag)
<span>{{$tag}}</span>
@endforeach
</div>
你應該試試這個:
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@endif
@endforeach
</div>
希望這對你的工作!
如果你的關鍵是numenric和索引數組它可以直接做到像:
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@else
<?php break; ?>
@endif
@endforeach
OR試試這個;
<div class="tag-area">
<?php $cnt == 0; ?>
@foreach(explode(',',$product->tags) as $tag)
<span>{{$tag}}</span>
<?php
$cnt++;
if($cnt >= 5)
break;
?>
@endforeach
記住break;
如果你有數組10元無需迭代後4迭代所以你應該打破的foreach迭代
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key=>$tag)
@if($key >= 4)
@break
@endif
<span>{{$tag}}</span>
@endforeach
</div>
由於您使用的是「explode()」,所以鍵將始終爲數字:-) –
是的,您是對的.. @MagnusEriksson。但如果OP要爲其他foreach然後它的唯一建議:) –
不必要的執行幫你。
<div class="tag-area">
@foreach(explode(',',$product->tags) as $key => $tag)
@if($key <= 5)
<span>{{$tag}}</span>
@endif
@endforeach
</div>
這將停止循環
爲什麼張貼重複的答案?答案也已被接受。你的答案和* AddWeb Solution Pvt Ltd *答案是什麼? –
同樣的事情,你已經在你以前的答案也.. .. https://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application/45650001 #45650001 https://stackoverflow.com/questions/42339534/cant-answer-incoming-call-in-android-marshmallow-6-0/45649908#45649908 –
@Hola它爲你工作還是沒有? –