dongxiong1935 2019-04-20 15:23 采纳率: 0%
浏览 281
已采纳

使用PHP获取JSON属性名称,后跟项目名称值

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.

enter image description here

  • 写回答

2条回答 默认 最新

  • dro80463 2019-04-20 15:43
    关注

    You are almost there, you just need to output the key name in the first loop, so

    foreach ($data as $products) {
    

    Is the bit which loops over the items Specials etc. So first grab the key in the foreach() and just output this as the first thing in the loop...

    foreach ($data as $key => $products) {
        echo $key."<br>";
    

    (No }) Will give...

    Specials<br>Shirt<br>cot...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?