0
    {
    "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'];
3
  • Do a print_r of $data to see PHP's data structure it got out of the JSON. Commented Jul 25, 2016 at 15:48
  • 1
    $data['books'][0]['images'][0]["320x180"]; Commented Jul 25, 2016 at 15:51
  • $image = $data['books'][$x]['images'][0]["320x180"]; yeah, this solved my problem. Commented Jul 25, 2016 at 15:56

2 Answers 2

2
function getImageLinksFor($json, $dimension='650x320') {
    $links      =   array();
    $objJson    = json_decode($json);

    // GET THE MAIN BOOKS OBJECT...
    $books = $objJson->books;

    // LOOP THROUGH THE $books OBJECT AND PERFORM YOUR SEARCH FOR IMAGES
    foreach ($books as $obj) {
        // SINGLE OUT THE IMAGES OBJECT
        $images = $obj->images;
        // SINCE IT IS ALSO AN ARRAY, SIMPLY LOOP THROUGH IT AND FETCH THE DESIRED DIMENSION.
        foreach ($images as $key => $objImgData) {
            if(property_exists($objImgData, $dimension)){
                $links[] = $objImgData->$dimension;
            }
        }
    }
    if(count($links) == 1){
        return implode("", $links);
    }
    return $links;
}

var_dump(getImageLinksFor($json, '650x320'));
Sign up to request clarification or add additional context in comments.

Comments

1

'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']
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.