我试图循环一个关联数组,但得到一个未定义的索引错误。
下面是数组。
{
"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 :(得分: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/>";
}
}