获取子数组的值而不循环两次?

时间:2012-06-14 20:59:18

标签: php oop foreach php-5.3

我将数组转换为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;
}

1 个答案:

答案 0 :(得分:0)

是的,我知道:

foreach ($items as $key => $item) 
{
    $array = (object) array_shift($item);

    echo $array->quantity_request.'<br />';
}

我希望我回答你的问题,100%不理解。

修改

<?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 />