非法字符串偏移&试图获得非物体的属性(laravel 5.3)

时间:2017-07-04 08:02:41

标签: php arrays foreach laravel-5.3 laravel-blade

所以我有问题在刀片中打印数据来自控制器的结果,所以:

  1. UseController.php:

         $expertCategory = Category::getCategoryByID($user_id);
         $data = [ 'expertCategory' => $expertCategory ];
         return view('cms.user.edit', $data);
    
  2. Category.php(models)getCategoryByID($ user_id)返回结果数组if i dd(expertCategory);在控制器中,结果是:

    array:9 [▼
       "id" => 1
       "name" => "Beauty"
       "sequence" => 1
       "background_color" => "ffffff"
       "status" => "Active"
       "created_at" => "2017-06-19 09:41:38"
       "updated_at" => "2017-06-19 09:41:38"
       "icon_filename" => "beauty-icon"
       "iconURL" => array:3 [▼
                "small" => "http://localhost:8000/images/category_icons/small/beauty-icon"
               "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon"
         ]
    ]
    
  3. 但是当我想使用foreach打印blade.php中的结果时,代码为:

     @foreach($expertCategory as $expertCat)
       {{ $expertCat->id }}
     @endforeach
    
  4. 将返回错误“试图获取非对象的属性”

    如果我使用这样的代码:

    @foreach($expertCategory as $expertCat) {{ $expertCat['id'] }} @endforeach

    它将返回:“非法字符串偏移'id'”

    任何人都可以帮助解决这个问题:s?非常感谢!

1 个答案:

答案 0 :(得分:0)

由于$expertCategory是一个dimensional array,您面临此问题

只需替换此

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => $expertCategory ];
return view('cms.user.edit', $data);

使用

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => [$expertCategory] ];
return view('cms.user.edit', $data);

然后使用

@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
@endforeach

在你的刀片中它会对你有用。