在laravel刀片中获取对象数组

时间:2017-05-29 05:51:09

标签: php laravel-5.4

正在开发像Olx这样的网站。 我想在菜单栏中附加主要类别和子类别。 我为每个元素获取这样的返回对象: enter image description here

我的控制器代码是:

$all_categories = [];
        $main_categories_name = Category::where('parent_id', 0)->pluck('name')->toArray();
        $main_categories_id = Category::where('parent_id', 0)->pluck('id')->toArray();        
        foreach($main_categories_id as $id){
          $name = Category::where('id', $id)->pluck('name');
          $sub_categories = Category::where('parent_id', $id)->pluck('name')->toArray();
          $all_categories[] = array('name' => $name, 'sub_categories' => $sub_categories);
        } 
        return $all_categories;

如何在刀片中获取这些元素?

@foreach($all_categories as $category) 
                @foreach($category['name'] as $category) 
                  <li id="{{$category}}" name="{{$category}}" class="dropdown-submenu main_category"> <a class="maincategory" tabindex="-1" href="#"><span class="categoryname">{{$category}}</span></a>
                    <ul class="dropdown-menu">
                      <li class="subcategory" id="subcat"> sub_category
                      </li>
                    </ul>
                  </li>
                @endforeach
            @endforeach
我是这样用过的。现在我想在我提到sub_category的名称中使用sub_categories。

我是这样的: enter image description here

使用此代码后:

<ul class="dropdown-menu multi-level">
            @foreach($all_categories as $category)                 
              <li id="{{$category['name']}}" name="{{$category['name']}}" class="dropdown-submenu main_category"> <a class="maincategory" tabindex="-1" href="#"><span class="categoryname">{{$category['name']}}</span></a>
                <ul class="dropdown-menu">
                @foreach($category['sub_categories'] as $category) 
                  <li class="subcategory" id="subcat"><a href="#">{{$category}}</a></li>
                @endforeach
                </ul>
              </li>
            @endforeach
            </ul>

该怎么办?我得到像这样的空阵列? enter image description here

1 个答案:

答案 0 :(得分:0)

返回视图刀片以及该变量的压缩:

return view('yourblade',compact('all_categories'));

然后在刀片文件中,使用foreach来解析子类别:

foreach($all_categories as $category)

格式化:

@foreach($all_categories as $category) 
    {{ $category['name'] }} // Prints men,... - format with your 
    @foreach($category['sub_categories'] as $subcategory) {
        {{ $subcategory }}  // Prints all your sub-categories under men,...
    @endforeach
@endforeach