0

So this may end up being a simple question but I have some code that looks at a JSON string and currently returns the image at array point 0 but I would like it to iterate for all the "hits" for this example there are 15 hits.

I imagine its a for each loop but i've searched and tried and cant figure it out. Any help would be greatly appreciated.

Here is my code

$content = curl_exec($ch);
$data = json_decode($content);
$jim = $data->hits[0]->thumbnailUrl;
echo "<img src='" . $jim . "' alt='error'>";

currently this code displays one image but I would like it to display for all the images its hits on. I can manually change which image it displays by changing the value hits[0] to be hits[2] for example.

j.baegs
  • 209
  • 2
  • 13
  • 1
    Does this answer your question? [How to loop through objects in php](https://stackoverflow.com/questions/8664208/how-to-loop-through-objects-in-php) – user3783243 Sep 02 '20 at 11:33

2 Answers2

1

Simple foreach will do:

$content = curl_exec($ch);
$data = json_decode($content);

foreach ($data->hits as $thumb) {
    printf('<img src="%s" alt="error">', $thumb->thumbnailUrl);
}
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
1
$content = curl_exec($ch);
$data = json_decode($content);
$hits = $data->hits;

foreach ($hits as $hit)
{
    
    echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
}

You can try this with a foreach loop to loop through your JSON data.