我已经将数组转换为这样的 stdClass 对象,
stdClass Object
(
[1339697186] => stdClass Object
(
[1403873546800880] => stdClass Object
(
[quantity_request] => 2
[time_created] => 1339697190
[variant] => stdClass Object
(
[0] => 1403873546800887
)
)
)
[1339697196] => stdClass Object
(
[1403873546800880] => stdClass Object
(
[quantity_request] => 1
[time_created] => 1339697196
[variant] => stdClass Object
(
[0] => 1403889656952419
)
)
)
)
所以如果我想得到[quantity_request]
每个项目,我会循环两次来得到答案,
foreach ($items as $key => $item)
{
foreach ($item as $code => $item)
{
echo $item->quantity_request;
}
}
我想知道是否有一种方法可以在不循环对象数组两次的情况下获得下面这样的答案?
foreach ($items as $key => $item)
{
# Get the product code of this item.
$code = $cart->search_code($key);
echo $item->$code->quantity_request;
}
错误:
致命错误:不能在...中使用 stdClass 类型的对象作为数组
我在一个类中有一个方法可以从对象数组的内容中获取代码(子键)。
public function search_code($key)
{
# Get this item.
$item = $this->content[$key];
# Get this item's sub key, which is the code of the product.
$subkeys = array_keys($item);
# Get the first item from the array.
$code = $subkeys[0];
# Return the sub key which is the code of the product.
return $code;
}