dongzhong9055 2017-05-27 12:09
浏览 55
已采纳

当我在laravel 5.2中使用foreach迭代时,Json解码

So I have a table called Categories and this is his Seeder file:

SubCategories::create(array(
        'id' => '1',
        'category' => 'Books',
        'image' => '2.png',
        'subcategory' => '{"0":"Action","1":"Drama","3":"Romance","4":"Biography", "5":"Mystery"}'
    ));

What I want to do is to echo this in a view file:

@foreach($SubCategories as $SubCategory)
   <li>
     <figure>
       <div><img src="pictures/images/{{$SubCategory->image}}"></div>
         <figcaption>
             <h3>{{$SubCategory->category}}</h3>
             <br>
             <div class="cat_men">
                 <a href="#">{{$SubCategory->subcategory}}</a>
             </div>
         </figcaption>
    </figure>
  </li>
@endforeach

This unfortunately echoes back at my site something like this:

{"0":"Action","1":"Drama","3":"Romance","4":"Biography","5":"Mystery"}

I so when I try to use json_decode function with the following code:

@foreach(json_decode($SubCategory->subcategory,true) as $sub)
   <li> {{$sub->sub[0]}} </li>
@endforeach

I get the following error:

ErrorException in de1a4fc568193a3fb9e08163f0b034f349f40fd8.php line 51: Trying to get property of non-object

This is my controller:

public function getIndex() { 
   $SubCategories = SubCategories::all();
   return view('shop.index')->with('SubCategories',$SubCategories);
}

Anyone has any idea for this problem? Any help will be appreciated!

  • 写回答

1条回答 默认 最新

  • duanditang2916 2017-05-27 12:15
    关注

    Just use

    {{$sub}} 
    

    instead of

    {{$sub->sub[0]}} 
    

    as you are already looping through the decoded JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料