Mark
Mark

Reputation: 783

How to do a foreach loop from JSON that comes from within a JSON

My code below is to retrieve and decode JSON data. The thing is that I am also retrieving a JSON file that came within the first one. And from that second one I want to display an image.

$json = @file_GET_contents('https://www.url.com/api?app_id='.$app_id.'&token='.$token.'&limit=10');
$results = json_decode($json, true)['result'];

foreach ($results as $json) {
$json = @file_GET_contents(''.$json['url'].'?app_id='.$app_id.'&token='.$token.'');
$details = json_decode($json, true);
$img = $details['image'];
}

echo '<ul>';
foreach ($results as $result) {
echo '<li>';
echo '<span><p>'.$result['name'].'</p></span>';
echo '<span><p>'.$result['title'].'</p></span>';
echo '<span><img src="'.$img.'"></span>';
echo '</li>';
}
echo '</ul>';

Below is an example of the first JSON response from which I get and decode "url":

{
"count": 10,
"total": 362,
"results": [
{
"name": "Example 1",
"url": "https://url.to.info1.json",
"title": "Example 1"
},
{
"name": "Example 2",
"url": "https://url.to.info2.json",
"title": "Example 2"
}
]
}

The second json file.:

{
"title": "Example",
"description": null,
"image": "https://url.to.image/"
}

With my code above it only display's one and the same image. I have tried multiple things but cannot think of a solution.

Upvotes: 1

Views: 243

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You are over-writing $img variable again and again inside loop, so same image showing each time.

Solution: Use key of $result variable to add image URL to $result variable itself:

foreach ($results as $key=>$json) { //use key
   $json = file_get_contents(''.$json['url'].'?app_id='.$app_id.'&token='.$token.'');
   $details = json_decode($json, true);
   $results[$key]['image'] = $details['image']; // based on key add image URL
}

echo '<ul>';
foreach ($results as $result) {
  echo '<li>';
  echo '<span><p>'.$result['name'].'</p></span>';
  echo '<span><p>'.$result['title'].'</p></span>';
  echo '<span><img src="'.$result['image'].'"></span>'; // Use `$result` variable now
  echo '</li>';
}
echo '</ul>';

Note:- don't use @ (error suppressor) and file_GET_contents needs to be file_get_contents

Upvotes: 1

Related Questions