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

时间:2019-04-20 15:23:57

标签: php json object

我正在尝试使用PHP通过JSON进行解析,然后打印出父属性的名称,后跟各项。

这是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
}]
}

我用下面的方法来遍历它:

$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/>";
}
}

输出为:

衬衫 棉衬衫 红色25.8 绿色26.5 短裤 一种尺寸 15.99 ...

我想先打印属性的名称,然后显示其中的项目,它应该像这样:

特价

衬衫 棉衬衫 红色25.8 绿色26.5

短裤 一种尺寸 15.99 ...

跳线

淡红色 轻巧 22.99

Bazoo护理 冬天的理想之选 32.99

我已将其添加为外部嵌套循环:

foreach ($data as $products => $value) {
echo $products;}

但这只会返回第一个对象名称。如何实现以上目标?

这是JSON的可视化。

enter image description here

2 个答案:

答案 0 :(得分:0)

将您json转换为数组并循环遍历

 $data = json_decode($readjson, true);

我们在这里传递true参数,这意味着没有对象的数组。

foreach($data as $key => $value){
  foreach($value as $k => $v){
     echo '<b>'.$v['name'].'</b> '.' '.$v['dsc'];
     echo isset($v['price']) ? $v['price'] : ' ';
     if(array_key_exists('vari', $v)){
        $vari = array_column($v['vari'], 'price','name');
        foreach($vari as $_k => $_v){
            echo $_k.' '.$_v;
        }
     }
     echo '<hr>';
  }
}

结果:-

Shirt cotton shirt red 25.8green 26.5
shorts one size15.99
shoes black shoes capri 37.8shooters 28.5
Glax Red thin lightweight22.99
Bazoo Care ideal for winter32.99

答案 1 :(得分:0)

您快到了,只需要在第一个循环中输出密钥名称,所以

foreach ($data as $products) {

是在Specials等项上循环的位。因此,首先抓住foreach()中的键,然后将其作为循环中的第一件事输出...

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

(否}) 会给...

Specials<br>Shirt<br>cot...