2012-02-03 54 views
0

我可以知道如何使用PHP中的foreach循環獲取「產品」值嗎?如何從嵌套數組中獲取數據

Array 
(
    [0] => Array 
     (
      [product] => "Sony" 
     ) 

    [1] => Array 
     (
      [product] => "Toshiba" 
     ) 

    [2] => Array 
     (
      [product] => "A4Tech" 
     ) 

) 

這是我的代碼,我知道它沒有工作後,我試了一下。

foreach($response as $key => $value){   

    foreach($key as $pic_small => $value2){ 

    echo $pic_small; 
    } 
} 

回答

4
foreach($response as $item) 
    echo $item['product']; 

PS:好吧,foreach語句花費$響應陣列的每一級元素,並將等於它$項變量(你不需要的元素的索引,所以代替$key => $value$value可用於)。在第一個循環中,它與$item = array('product' => 'Sony');相同,在第二個循環中它與$item = array('product' => 'Toshiba');等相同。

您當然可以使用第二個foreach循環來處理這些數組,但是如果您只需鍵入一個關聯元素的值product,然後您可以直接通過$item['product']的值訪問它。

否則,因爲它是在另一個答案所示,你可以做它作爲

// $item1 means element of the first level in the original array 
// $key2 and $value2 are keys and values of the second level elements 
foreach($response as $item1) 
    foreach($item1 as $key2 => $value2) // you may remove '$key2 =>' here 
     echo $value2; 
+0

護理寫一個句子?它非常猖獗,但是將Stackoverflow轉換爲代碼轉儲並不是很好的風格。 – mario 2012-02-03 04:17:28

+0

@mario但代碼非常明顯,不需要任何解釋。 – Cheery 2012-02-03 04:18:18

+0

這是非常非常。但顯然不是OP。 – mario 2012-02-03 04:18:45

0
foreach($response as $key => $value){   

    foreach($value as $title => $value2){ 

     echo $value2; 
    } 
} 
+1

這是正確的答案。除了它也缺少解釋部分。 – mario 2012-02-03 04:15:15