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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题