I am trying to loop through a nested array which is in my JSONObject. My aim is to echo div's based on the data in the JSONObject currently I am using this to get the contents of the JSON
$restaurant = json_decode(file_get_contents("restaurant.json"));
Here is the old foreach loop before I nested the array
<?php foreach($restaurant->menu->starter as $starter){
echo '<h3>'.$starter->name.'</h3><br><p>'.$starter->price.'</p><br>';
} ?>
And here is my new JSONObject
{
"name": "Takeaway Kings",
"menu": [
{
"starter": [
{
"name": "Samosas",
"price": 3.5
},
{
"name": "Chaat",
"price": 1.99
}
]
},
{
"dessert": [
{
"name": "Kulfi",
"price": 2.5
},
{
"name": "Kheer",
"price": 2.99
}
]
},
{
"main": [
{
"name": "Lamb Biryani",
"price": 4.5
},
{
"name": "Chicken Tikka Masala",
"price": 5.99
}
]
}
]
}
I am not sure how to for example write this loop just for the starters data to display
$arr = json_decode($json); // $json is your JSON.
foreach($arr->menu[0]->starter as $starter){
echo '<h3>'.$starter->name.'</h3><br><p>'.$starter->price.'</p><br>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.