如何删除laravel中foreachloop的最后一项中的逗号?

时间:2016-10-12 05:38:48

标签: php laravel foreach

我尝试使用if条件添加最后一项逻辑,但代码正在显示。

我现有的代码:

<script type='application/ld+json'> 
{
  "itemListElement":
[
  @foreach($product->Offers as $offer)
   {
    "@type": "Offer",
    "name": "{{$offer->title}}",
    "price": "{{$offer->displayPrice}}",
   },  
   @endforeach 
 ]
}

}
</script>

2 个答案:

答案 0 :(得分:3)

尝试使用$loop->last()

@foreach($product->Offers as $offer)
{
    "@type": "Offer",
    "name": "{{$offer->title}}",
    "price": "{{$offer->displayPrice}}",
}{{ $loop->last() ? '' : ',' }}
@endforeach 

答案 1 :(得分:1)

尝试这样做

<?php $i = 1; $len = count($product->Offers); ?>
@foreach($product->Offers as $offer)
  {
  "@type": "Offer",
  "name": "{{$offer->title}}",
  "price": "{{$offer->displayPrice}}",
  }<?php if($i < $len){echo ',';} $i++;?>
@endforeach