sukkis sukkis - 4 months ago 26
PHP Question

Parse multi level json data with php

{
"books": [
{
"id": 2331,
"image": "http://lol.org/flower.png",
"images": [
{
"256x144": "http://lol.org/bee.png",
"650x320": "http://lol.org/fly.png"
}
],

....


I have json data like above but my problem is how to get out 650x320 data.

$data = json_decode($jsondata,true);
$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++){


Codes below works fine

$image = $data['books'][$x]['image'];


but how to fetch images on a second json level? I have tried code below with no luck.

$image = ($data->{'books'}->{'images'}->{'320x180'});

$image = $data['books']['images'][$x]['320x180'];

Lew Lew
Answer

'books' is an Array of objects, you will need to select an object using a numeric index.

$image = $data['books'][$insertIndexHere]['images'][$insertIndexHere]['320x180'];

Essentially you have missed the [$x] between 'books' and 'images' from your first code which works.

You will probably want a loop which iterates through each book and then a second nested loop which iterates through the images in each book.

For example:

$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++) {
   $images = data['books'][$x]['images'];
   $sizeOfImages = sizeof($images);
   for($j = 0; $j < $sizeOfImages; $j++) {
      // access $images[$j]['320x180']
   }
}