2017-05-27 12:09
浏览 55

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

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

        '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)
       <div><img src="pictures/images/{{$SubCategory->image}}"></div>
             <div class="cat_men">
                 <a href="#">{{$SubCategory->subcategory}}</a>

This unfortunately echoes back at my site something like this:


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>

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


    instead of


    as you are already looping through the decoded JSON.

    解决 无用
    打赏 举报

相关推荐 更多相似问题