dongquepao8653
2016-10-12 05:38
浏览 93
已采纳

如何删除laravel中foreach循环的最后一项中的逗号?

I tried adding last item logic using if condition, but the code is getting displayed.

My existing code :

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

}
</script>

图片转代码服务由CSDN问答提供 功能建议

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

我现有的代码:

 &lt; script type ='application / ld + json'&gt;  
 {
“itemListElement”:
 [
 @foreach($ product-&gt; offer as $ offer)
 {
“@type”:“Offer”,
“name”:“{{  $ offer-&gt; title}}“,
”price“:”{{$ offer-&gt; displayPrice}}“,
},
 @endforeach 
] 
} 
 
} 
&n&lt;  ; / script&gt; 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drkjzk3359 2016-10-12 05:57
    已采纳

    Try to do this

    <?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
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duano3557 2016-10-12 05:46

    Try to use $loop->last():

    @foreach($product->Offers as $offer)
    {
        "@type": "Offer",
        "name": "{{$offer->title}}",
        "price": "{{$offer->displayPrice}}",
    }{{ $loop->last() ? '' : ',' }}
    @endforeach 
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题