在尝试使用 for 循环显示结果时尝试获取非对象的 属性 'prd_name'

Trying to get property 'prd_name' of non-object while trying to show results with for loop

我想用 for loop 从数据库中检索一些数据,所以在控制器中,我添加了这个:

$foundOrder = Cart::select('crt_content')->whereCrtId($cart->crt_id)->latest()->first();
$foundOrder = json_decode($foundOrder->crt_content);

if ($foundOrder != null) {
   foreach ($foundOrder as $key => $value) {
      $prds[] = [
          Product::with('uploaded')->wherePrdId($value->id)->select('*')->first(),
          $value->quantity,
          $value->price
      ];
   }
} else {
   $prds = [];
}

所以 $prds 是一个数组,如果我这样做 {{ dd($prds) }},我得到这个:

所以在 Blade,我尝试了这个:

@for($i=0;$i<=count($prds);$i++)
   {{ $prds[$i]->prd_name }}
   {{ $prds[$i]->prd_sale_price }}
@endfor

但是returns这个错误:

Trying to get property 'prd_name' of non-object

所以这里出了什么问题?正如您在图片中看到的,我正在获取所有现有产品及其属性(例如 prd_idprd_nameprd_sale_price)。

您正在 $prds 数组中存储产品对象、数量和价格。你有数组中的数组。使用下面的代码

使用foreach循环

@foreach($prds as $data)
  // in data 0 index will your product object,1 will be quantity and 2 will be price
   {{ $data[0]->prd_name }} // prd_name from product object
   {{ $data[0]->prd_sale_price }}
@endforeach

// 使用 for 循环

@for($i=0;$i<count($prds);$i++)
   {{ $prds[$i][0]->prd_name }} 
   {{ $prds[$i][0]->prd_sale_price }}
@endfor

您的 $prds 是一个数组,每个元素都具有以下结构:

[
    product,
    quantity,
    price
];

所以如果你遍历它并想得到一个产品的属性,你需要从$prds[$i][0]中得到它,例如:$prds[$i][0]->prd_name.

更新: 您需要从索引 0 循环到 count($prds) - 1

@for($i = 0; $i <= count($prds) - 1; $i++)