foreach不适用于子数组

foreach不适用于子数组

本文介绍了PHP foreach不适用于子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要弄清楚如何使以下内容起作用。

I need to work out how to do I get the following to work.

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

I have an array with sub-array

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

然后当我将该数组放入我的foreach时

then when I put that array thought my foreach

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

                </tr>
                <?php
                }
            }
       ?>

我似乎无法访问项目的子数组。

I can't seem to access the sub array for items. What I want to be able to do is call it like

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

编辑

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

I am getting the data from MongoDB by the following code

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;
        }
    }

当我执行打印输出时会返回

which when I do a print out returns

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


推荐答案

您应该替换

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

这篇关于PHP foreach不适用于子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:51