你好。我正在尝试使用 JSON 获取 PHP 数组并按国家/地区显示所有城市名称。什么都不输出。Json 有效,请在此处检查。我的错误是什么?
$json[] = file_get_contents('http://turmagnat-demo.ideaperm.ru/hotels/Output_1.json');
$array = json_decode($json, true);
$country = "Ямайка";
$city = "";
foreach ( $array as $key => $value){
if($value['country'] == $country) {
$city .= $value['city'];
}
}
echo $city;
JSON 文件示例:
[
{
"id": "al130489",
"sourceUrl": "http://tophotels.ru/hotel/al130489",
"country": "США",
"city": "Висконсин",
"name": "Hilton Garden Inn Appleton/Kimberly 3*",
"description": null,
"reviews": [],
"images": []
},
{
"id": "al277646",
"sourceUrl": "http://tophotels.ru/hotel/al277646",
"country": "Италия",
"city": "Лидо ди Камайоре",
"name": "Villa Il Fortino",
"description": null,
"reviews": [],
"images": []
}
]
也许您徒劳地将数据放入数组中,试试这个
并且最好总是检查 json 是否已经被转换为数组,否则你会得到一个无效的参数提供 foreach 错误,json_decode将返回NULL而不是数组以防出错,所以最好像这样:
或者