php - 如何从来自 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/"
}
使用上面的代码,它只显示一个相同的图像。我尝试了多种方法,但想不出解决方案。
解决方案
您$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
推荐阅读
- android - 0 支持安卓设备,上传新版本后
- php - CodeIgniter:Ajax 更新和删除不起作用
- assembly - 调整堆栈指针以推动函数的争论
- windows - 如何在 Windows 批处理文件中的 HH:29:55 和 HH:59:55 触发命令
- php - 当我登录每个用户的帐户时,如何重定向每个页面。我希望他们重定向到各自的页面(codeIgniter)
- c++ - 从没有外部“C”的dll中导出C++函数
- node.js - Win10 Professional Dockerizing Augular App 给出:未知指令:EXPAND-ARCHIVE
- php - 所提交的网址带有不被接受的字符。URL 是`https://www.carlo.in/car_offers#getDiscounts?key=test`
- django - 链式表单填写django表单
- python - 意外的导入行为:导入了不存在的模块