2017-08-12 46 views
1

在foreach循环中可能有5或6个值,但我需要打印假设前5或6个值。我该怎么做?如何在foreach循环中只打印4个值?

<div class="tag-area">       
     @foreach(explode(',',$product->tags) as $tag)       
      <span>{{$tag}}</span> 
     @endforeach      
</div> 

回答

2

你应该试试这个:

<div class="tag-area">       
    @foreach(explode(',',$product->tags) as $key => $tag) 
     @if($key <= 5)       
      <span>{{$tag}}</span> 
     @endif 
    @endforeach      
</div> 

希望这对你的工作!

+0

@Hola它为你工作还是没有? –

0

如果你的关键是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> 
+0

由于您使用的是“explode()”,所以键将始终为数字:-) –

+0

是的,您是对的.. @MagnusEriksson。但如果OP要为其他foreach然后它的唯一建议:) –

0

不必要的执行帮你。

<div class="tag-area">       
     @foreach(explode(',',$product->tags) as $key => $tag) 
      @if($key <= 5)       
       <span>{{$tag}}</span> 
      @endif 
     @endforeach      
    </div> 
1

这将停止循环

+0

为什么张贴重复的答案?答案也已被接受。你的答案和* AddWeb Solution Pvt Ltd *答案是什么? –

+0

同样的事情,你已经在你以前的答案也.. .. 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 –