【发布时间】:2012-06-14 20:59:17
【问题描述】:
我已经像这样将数组转换为 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;
}
【问题讨论】:
-
注意:在双 foreach 中使用两个 $item 变量会导致问题。
-
@ben:我不确定它是否会导致问题,我认为阴影会按预期执行。但我同意它令人困惑/不清楚。