PHP - error: '试图获取非对象属性'当尝试使用购物车数组元素分配变量时


PHP - error: 'Trying to get property of non-object' when trying to assign variables with shopping cart array elements

我有一个下面的数组:

    `print_r($cart);` 

Array ([eccbc87e4b5ce2fe28308fd9f2a7baf3] => Array ([id] => 3 [qty])=> 3[price] => 89.19 [name] => null [rowid] => eccbc87e4b5ce2fe28308fd9f2a7baf3[subtotal] => 267.57)

但我不能找出一种方法来读取单独的行。

标准格式:

foreach ($cart as $item):
    $id = $item->id;
    <...>

给了我标题中提到的错误…

那我怎么读呢?

当它是数组时,您试图将其作为对象(->)访问。你要做的是:

foreach ($cart as $key => $item):
    $id = $item['id'];
endforeach;

指出

  • 数组被这样访问:variable[array_index]
  • 当对象被这样访问时:variable->object_index