【问题标题】:Get the value of a sub array without looping twice?在不循环两次的情况下获取子数组的值?
【发布时间】: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:我不确定它是否会导致问题,我认为阴影会按预期执行。但我同意它令人困惑/不清楚。

标签: php oop foreach php-5.3


【解决方案1】:

是的,据我所知:

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

【讨论】:

  • 请注意:每个顶级对象都只有一个二级对象(正如他发布的print_rs 建议的那样)。但是如果他的每个顶级对象有多个二级对象,它会跳过一些,而他的双循环解决方案不会。
  • @jedwards 是的,我知道。但是在示例中我只在第二层看到了一个条目,所以我猜……让我们看看他的答案。
  • 感谢 David Bélanger 的回答。我认为它适用于您的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-12-01
  • 2013-05-19
  • 2013-01-06
  • 1970-01-01
  • 2018-06-02
  • 2021-11-06
  • 2015-03-06
  • 2011-12-21
相关资源
最近更新 更多