0

I am trying to extract different info from a json returned output via json_decode, however I cannot seem to access the info:

JSON:

{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},

PHP:

$photos = json_decode($json);
foreach($photos as $photo){
$id = $photo->id;
$owner = $photo->owner;
$secret = $photo->secret;
echo $id.'<br/>';
echo $owner.'<br/>';
echo $secret.'<br/>';
}
rainerbrunotte
  • 907
  • 1
  • 17
  • 37
  • 2
    Seems like you have to do `foreach($photos->photo as $photo)`. If you pretty print the json (ie by using jsonlint.com) the data structure should be quite clear – JimL Nov 13 '17 at 21:27
  • 1
    Actually, just a little more depth `foreach($photos->photos->photo as $photo)` – Jay Blanchard Nov 13 '17 at 21:35
  • Odd setup of the json object. Almost like it got improperly made stuffing everything first under "photos", when that should have been the array of whats under the singular "photo" (which oddly refers to many). – IncredibleHat Nov 13 '17 at 21:42

1 Answers1

1

Because of the depth of the JSON you have to start your loop at the right level. Here is an example:

$json = '{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0}]}}';

$photos = json_decode($json);

foreach($photos->photos->photo as $photo){
 $id = $photo->id;
 $owner = $photo->owner;
 $secret = $photo->secret;
 echo $id.'<br/>';
 echo $owner.'<br/>';
 echo $secret.'<br/>';
}

Note the first level in your JSON is "photos" and the second is "photo".

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119