I am trying to parse through a JSON using PHP then print the name of the parent property followed by the items.
Here's the JSON
{
"Specials": [{
"name": "Shirt","dsc":"cotton shirt",
"vari": [{ "name":"red", "price":25.80 },{ "name":"green", "price":26.50 }]
},
{
"name":"shorts","dsc":"one size","price":15.99
},
{
"name":"shoes","dsc":"black shoes",
"vari": [{ "name":"capri", "price":37.80 },{ "name":"shooters", "price":28.50 }]
}],
"Jumpers": [{
"name": "Glax Red","dsc":"thin lightweight","price":22.99
},
{
"name": "Bazoo Care","dsc":"ideal for winter","price":32.99
}]
}
I have used following to iterate through it:
$readjson = file_get_contents('products.json') ;
$data = json_decode($readjson);
foreach ($data as $products) {
foreach ($products as $product) {
echo $product->name."<br>".$product->dsc."<br>";
if (isset($product->price))
{
echo " ".$product->price."<br>";
}
else {
foreach ($product->vari as $var) {
echo $var->name." ".$var->price."<br/>";
}
}
The output is:
Shirt cotton shirt red 25.8 green 26.5 shorts one size 15.99 ...
I'd like to print the name of the property first then show the items that are within it, it should look like this:
Specials
Shirt cotton shirt red 25.8 green 26.5
shorts one size 15.99 ...
Jumpers
Glax Red thin lightweight 22.99
Bazoo Care ideal for winter 32.99
I've added this as the outer nested loop:
foreach ($data as $products => $value) {
echo $products;}
But that only returns the first object name. How can I achieve the above?
Here's a visualisation of the JSON.