【问题标题】:PHP foreach not working with sub-arrayPHP foreach 不适用于子数组
【发布时间】:2013-02-04 11:09:40
【问题描述】:

我需要弄清楚如何才能使以下工作正常进行。

我有一个带有子数组的数组

array (
  'session' => '1359964785.85203874781',
  'status' => 'cart',
  'items' => 
  array (
    'id' => '510bca8138fc5d6e38000000',
    'quantity' => '1',
  ),
)

然后当我把那个数组认为是我的 foreach 时

<?php
       $cart = Shop::get_cart();
       ;
            if($cart != NULL)
            { 
                foreach($cart[0]['items'] as $items)
                {
                    print $items['id'];
                ?>
                <tr>

                </tr>
                <?php
                }   
            }
       ?>

我似乎无法访问项目的子数组。我想做的就是这样称呼它

$items["id"];
$items["quantity"];

编辑

我通过以下代码从 MongoDB 获取数据

public function get_cart()
    {
        $collection = static::db()->redi_shop_orders;
        $cursor = $collection->find(array('session' => $_SESSION["redi-Shop"]));
        if ($cursor->count() > 0)
        {
            $posts = array();
            // iterate through the results
            while( $cursor->hasNext() ) {   
                $posts[] = ($cursor->getNext());
            }
            return $posts;
        }
    }

当我打印出来时返回

Array ( [0] => Array ( [_id] => MongoId Object ( [$id] => 510f8eba38fc5d7d43000000 ) [session] => 1359964785.85203874781 [status] => cart [items] => Array ( [id] => 510bca8138fc5d6e38000000 [quantity] => 1 ) ) )

【问题讨论】:

  • is_array($cart)? isset($cart[0])? isset($cart[0]['items'])? is_array($cart[0]['items'])? - 您可以自己进行一些非常基本的调试。

标签: php mongodb foreach arrays


【解决方案1】:

你应该替换

foreach($cart[0]['items'] as $items)

foreach($cart['items'] as $items)

【讨论】:

  • foreach($cart['items'] as $items)
  • var_dump($cart)你有什么?
【解决方案2】:
<?php
   $cart = array (
  'session' => '1359964785.85203874781',
  'status' => 'cart',
  'items' => 
  array (
 'id' => '510bca8138fc5d6e38000000',
'quantity' => '1',
 ),
);

        if($cart != NULL)
        { 
            foreach($cart['items'] as $items)
            {
                print $items['id'];
            ?>
            <tr>

            </tr>
            <?php
            }   
        }
   ?>

【讨论】:

  • 您能解释一下出了什么问题以及您是如何解决的吗?这样每个人都会很快清楚。
猜你喜欢
  • 2018-12-19
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多