循环通过深JSON树

时间:2012-11-04 08:44:31

标签: php json

JSON

[
  {
    "kind": "Listing"
  },
  {
    "kind": "Listing",
    "data": {
      "children": [
        {
          "data": {
            "body": "body1"
          }
        },

        {
          "data": {
            "body": "body2"
          }
        }
      ]
    }
  }
]

我想要遍历的部分:[{第一组值},{data-> children-> data-> body}

最后一个身体是我想抓住的部分。还有其他多组,每个“body”代表reddit上没有子项的单独注释。

2 个答案:

答案 0 :(得分:0)

json_decode将json放入一个对象然后循环:

<?php 
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.reddit.com/r/indie/comments/zc0lz/.json");
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$json = curl_exec($curl);
curl_close($curl);
//decode the json
$json_obj = json_decode($json);
//loop the result set(array) and access the data->children sub array.
foreach($json_obj as $v){
    foreach($v->data->children as $d){
        if(isset($d->data->body)){
            echo $d->data->body.'<br />'.PHP_EOL;
        }
    }
}

/*
Is anyone else bored with this? The first album was good for the moment it existed in, but the has since passed. It just seems their sound didn't mature very well.<br />
Yeah, from the songs I had heard, this album missed it. Too similar and not as exciting.<br />
half the album is just as amazing as the first. half is kind of dull<br />
Got this album today, maybe 2 decent-ish songs, but it sounds like they have tried to copy some of the sounds from the album way too closely. Real shame. 4/10<br />
If the player doesn't work, refresh the page and try again. You can also use the NPR link!<br />
Loved the sound of the first album, and I'm kind of happy they've not strayed to much away from this. Have to agree that it seems to be missing the 'awesomeness' that made the first songs so enjoyable to listen to.<br />
*/
?>

答案 1 :(得分:0)

为了以PHP对象和数组的形式将有效的Json字符串解码为PHP变量,您可以使用json_decode函数。

要遍历PHP变量中的值 - 尤其是数组和对象 - 您可以使用foreach

如果您在深树中找到要循环的值时遇到问题,请参阅

但是你还没有告诉你的实际的问题与Json字符串有什么关系,所以我只能用这种一般形式回答。