2013-02-04 31 views
1

我需要解決如何做到以下工作。PHP foreach不能與子陣列

我與子陣列

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

,當我做了打印out returns

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

'is_array($車)'? 'isset($車[0])'? 'isset($車[0] [ '項目'])'? 'is_array($車[0] [ '項目'])'? - 你可以自己做一些非常基本的調試。 – Leigh

回答

4

YOu should replace

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

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

沒有工作 – RussellHarrower

+0

什麼不起作用? – Baba

+0

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

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 
      } 
     } 
    ?> 
+0

你能解釋一下哪裏出了問題,以及如何修復它?這樣對每個人來說都會很快清楚。 –

+0

這仍然不起作用,也許是因爲我使用MongoDB? – RussellHarrower