循环并回显指定的JSON内容

时间:2018-08-28 11:37:41

标签: php arrays json

如何仅在“ wrapperType”:“曲目” 中显示 artistName

这是JSON示例:

{  
   "resultCount":5,
   "results":[  
      {  
         "wrapperType":"collection",
         "artistName":"Liam Payne"
      },
      {  
         "wrapperType":"track",
         "artistName":"Liam Payne & French Montana"
      }
      {  
         "wrapperType":"track",
         "artistName":"Liam Payne & French Montana"
      }
      {  
         "wrapperType":"track",
         "artistName":"French Montana"
      }
      {  
         "wrapperType":"track",
         "artistName":"French Montana"
      }
   ]
}

和php代码:

但这将显示所有值

foreach ($obj->results as $row){
    echo $row->artistName;
}

4 个答案:

答案 0 :(得分:4)

在代码中放入"engines": { "node": "8" }, 条件。

尝试以下代码:

if($row->wrapperType == "track")

答案 1 :(得分:0)

您需要在foreach循环中添加一个条件,以检查wrapperType是否为track

赞:

foreach ($obj->results as $row){
    if($row->wrapperType == "track"){
      echo $row->artistName;
   }
}

答案 2 :(得分:0)

foreach ($obj->results as $row){
    echo $row->artistName;
}

循环浏览所有可用项目。您应该检查wrapperType

foreach ($obj->results as $row){
  if ($row->wrapperType == 'track') {
    echo $row->artistName;
  }
}

答案 3 :(得分:0)

首先,您的json无效(缺少,),您可以检查所需的输出here

循环使用$data['results']代替$obj->results

在条件如if($row['wrapperType']=='track'){// if condition for what type of data you want下使用     

$data='{
    "resultCount": 5,
    "results": [{
            "wrapperType": "collection",
            "artistName": "Liam Payne"
        },
        {
            "wrapperType": "track",
            "artistName": "Liam Payne & French Montana"
        }, {
            "wrapperType": "track",
            "artistName": "Liam Payne & French Montana"
        }, {
            "wrapperType": "track",
            "artistName": "French Montana"
        }, {
            "wrapperType": "track",
            "artistName": "French Montana"
        }
    ]
}';
$data=json_decode($data, true);
print_r($data['results']);
foreach ($data['results'] as $row){
    if($row['wrapperType']=='track'){// if condition for what type of data you want
       echo "Artist Name: ".$row['artistName'];
       echo "Wrapper Type: ".$row['wrapperType'];
    }
}