Php 在不循环两次的情况下获取子数组的值?
我将数组转换成如下的stdClass对象Php 在不循环两次的情况下获取子数组的值?,php,oop,foreach,php-5.3,Php,Oop,Foreach,Php 5.3,我将数组转换成如下的stdClass对象 stdClass Object ( [1339697186] => stdClass Object ( [1403873546800880] => stdClass Object ( [quantity_request] => 2 [time_created] => 133
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 ($items as $key => $item)
{
$array = (object) array_shift($item);
echo $array->quantity_request.'<br />';
}
我希望我能回答你的问题,我没有100%的理解
编辑
注意:在double foreach中使用两个$item变量将导致问题。@ben:我不确定这是否会导致问题,我认为阴影将按预期执行。但我同意这一点,即它令人困惑/不清楚。只需注意:每个顶级对象都有一个第二级对象,正如他张贴的印刷品所建议的那样。但是,如果他每个顶级对象有多个二级对象,它会跳过一些,而他的两个循环解决方案不会。@jedwards是的,我知道。但在这个例子中,我只看到第二级的一个条目,所以我猜。。。让我们看看他的答案。谢谢大卫·贝兰格的回答。我认为这与你的答案是一致的。谢谢
<?php
$items = (object) array(
1339697186 => array(1403873546800880 => array('quantity_request' => 2)),
1339697187 => array(1403873546800880 => array('quantity_request' => 3)),
1339697188 => array(1403873546800880 => array('quantity_request' => 4))
);
foreach ($items as $key => $item)
{
$array = (object) array_shift($item);
echo $array->quantity_request.'<br />';
}
?>
// Results :
2<br />3<br />4<br />