1

我已经将数组转换为这样的 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;
}
4

1 回答 1

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 />
于 2012-06-14T21:02:33.827 回答