JSON解析php问题

时间:2016-02-26 08:44:24

标签: php json parsing

我有这个json回复

 {"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]}

我只需要从响应中提取random1,random2,random,3,这样最终的结果就是:

  • random1
  • random2
  • random3

我有这个脚本

$jsonData = file_get_contents("json");

$json = json_decode($jsonData,true); 

foreach($json["results"][0]["response"] as $data) {
 {
   echo json_encode($data);

}
}

但这只会提取

  • random1

如果我在[0]中更改[1],则会提取random2和[2] random3 如何立即获得random1,random2,random3,响应?所以最终的回声是:

  • random1
  • random2
  • random3

提前感谢您,任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

循环播放$json['result']您所做的只是第一个索引0,其中random1response

$json = '{"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]}';
$json = json_decode($json,true); 

foreach($json["results"] as $data) {
   echo $data['response'][0]."\n";
}

试试here

<强>更新

如果您想要过滤,请说random1,然后执行此操作

$json = json_decode($json,true); 
$filter = array("random1"); //You can add items to filter
$result = array();
foreach($json["results"] as $data) {
   if(!in_array($data['response'][0],$filter))
       $result[] = $data;
}
print_r($result);

$result仅包含random2&amp; random3

答案 1 :(得分:0)

results是一个数组,所以你得到了数组中的第一个:$json["results"][0]

如果要迭代所有值,它应该是这样的:

foreach($json["results"] as $data) {
   echo json_encode($data['response']);

}

答案 2 :(得分:0)

foreach($json["results"] as $data) {    echo json_encode($data['response']);}