2012-11-04 169 views
0

JSON通過深JSON樹循環

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

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

我通過要循環的部分:[{第一組值},{DATA-> CHILDREN->數據 - >體}

最後一部分是我想要抓的部分。還有其他幾套,每個「身體」代表在reddit上沒有孩子的單獨評論。

+1

第1步:製作JSON [有效](http://jsonlint.com)。 (你不能在JSON中使用懸掛逗號。) –

+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 /> 
*/ 
?> 
0

對於有效的JSON字符串轉換成在PHP對象和數組形式的PHP變量進行解碼,則可以使用json_decode功能。

要遍歷PHP變量中的值 - 特別是數組和對象 - 可以使用foreach

如果你有問題,找到你想要在深樹遍歷值,請參閱

但是你還沒有告訴你的實際問題與Json字符串是,所以我只能以這種一般形式回答。