Reputation: 259
I have a JSON Object and I am trying to write a foreach loop to output each record in an array. This is my JSON Object code
{
"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
}
]
}
}
and this is my PHP code
$restaurant = json_decode(file_get_contents("restaurant.json"));
$restaurant->menu[0];
foreach($starters as $starter){
$name = $starter->name;
$price = $starter->price;
//do something with it
echo $name + " . " + $price;
}
at the moment nothing is being output
Upvotes: 0
Views: 59
Reputation: 94662
If you look at a print_r($restaurant)
of the decodes JSON string always a good start point when you are not sure of the JSON syntax, you will see what structure it has.
stdClass Object
(
[name] => Takeaway Kings
[menu] => stdClass Object
(
[starter] => Array
(
[0] => stdClass Object
(
[name] => Samosas
[price] => 3.5
)
[1] => stdClass Object
(
[name] => Chaat
[price] => 1.99
)
)
[dessert] => Array
(
[0] => stdClass Object
(
[name] => Kulfi
[price] => 2.5
)
[1] => stdClass Object
(
[name] => Kheer
[price] => 2.99
)
)
[main] => Array
(
[0] => stdClass Object
(
[name] => Lamb Biryani
[price] => 4.5
)
[1] => stdClass Object
(
[name] => Chicken Tikka Masala
[price] => 5.99
)
)
)
)
Also in PHP the concatenation character is .
and not +
$restaurant = json_decode(file_get_contents("restaurant.json"));
print_r($restaurant);
foreach($restaurant->menu->starter as $starter){
echo $starter->name . ' = ' . $starter->price . PHP_EOL;
}
Will produce the output
Samosas = 3.5
Chaat = 1.99
Upvotes: 2
Reputation: 4739
Replace menu[0] with menu and $starter->name with $starter[0]->name and $starter->price with $starter[0]->price like this:
$restaurant = json_decode(file_get_contents("restaurant.json"));
$starters = $restaurant->menu;
foreach($starters as $starter){
$name = $starter[0]->name;
$price = $starter[0]->price;
//do something with it
echo $name + " . " + $price;
}
Upvotes: 1