2016-11-30 82 views
0

我試圖通過關聯數組循環但獲取未定義的索引錯誤。以下是數組。試圖通過關聯數組循環時獲取未定義的索引

{ 
    "first":{ 
     "name":"name 1", 
     "products":[ 
      { 
       "id":2, 
       "product_id":123, 
       "category_id":1 
      }, 
      { 
       "id":3, 
       "product_id":"456" 
      } 
     ] 
    } 
} 

我通過這個像

foreach ($array as $category => $products) { 
    echo $category; 
    foreach ($products['products'] as $product) { 
     echo $product->id; 
    } 
} 

試圖循環,但我得到一個

Undefined index: products 

我如何遍歷數組的產品?

+0

使用'$陣列= json_decode($陣列,TRUE);'循環 – jitendrapurohit

+0

什麼的定義之前'$ array'? – rbr94

回答

1

您需要更改$products['products']$products->products因爲 $products對象沒有陣列

$test='{"first":{"name":"name 1","products":[ 
{"id":2,"product_id":123,"category_id":1},{"id":3,"product_id":"456"} 
]}}'; 
echo "<pre>"; 
$array=json_decode($test); 
foreach($array as $category => $products){ 
    foreach($products->products as $product){ 
     echo $product->id."<br/>"; 
    }     
} 

demo.....

+0

$ test已經在數組中。所以我試過json_decode(json_encode($ my_array));然後像你說的那樣在foreach中運行數組。但我得到未定義的屬性:stdClass :: $產品 – Sid

+0

如果您的數據是json然後轉換數組,然後如果數組然後刪除json_decode。 –

+0

數據是數組,並試圖通過不傳遞它通過json_decode我得到「試圖獲得非對象的屬性」 – Sid