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


How to remove comma in last item of foreachloop in laravel?

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

我现有的代码:

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

尝试使用$loop->last():

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

试着这样做

<?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