首页 > 解决方案 > 如何从来自 JSON 的 JSON 执行 foreach 循环

问题描述

我下面的代码是检索和解码 JSON 数据。问题是我还在检索第一个文件中的 JSON 文件。从那第二个开始,我想显示一个图像。

$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>';

下面是我获取并解码“url”的第一个 JSON 响应的示例:

{
"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"
}
]
}

第二个json文件:

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

使用上面的代码,它只显示一个相同的图像。我尝试了多种方法,但想不出解决方案。

标签: phpjsonforeach

解决方案


$img在循环内一次又一次地覆盖变量,因此每次都显示相同的图像。

解决方案:使用key变量$result将图像 URL 添加到$result变量本身:

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>';

注意:-不要使用@ (error suppressor)file_GET_contents需要file_get_contents


推荐阅读