1

我需要弄清楚如何做才能使以下工作。

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

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 ) ) )
4

2 回答 2

4

你应该更换

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

foreach($cart['items'] as $items)
于 2013-02-04T11:11:10.620 回答
0
<?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
            }   
        }
   ?>
于 2013-02-04T11:20:15.673 回答