0

JSON

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

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

The parts I want to loop through: [{first set of values},{data->children->data->body}

That last body is the part I want to grab. There are multiple other sets of those, each "body" represents a seperate comment without children on reddit.

eveo
  • 2,797
  • 15
  • 61
  • 95

2 Answers2

0

json_decode the json into an object and then loop:

<?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 />
*/
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

For decoding a valid Json string into a PHP variable in the form of PHP objects and arrays, you can make use of the json_decode function.

To loop over values inside a PHP variable - especially arrays and objects - you can make use of foreach.

If you have a problem to find the values you want to loop over in the deep tree, please see

But you have not told what your actual issue with the Json string is, so I can only answer in this general form.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836