我有一个来自api的json回复,我想要一些数据。
响应如下:
{
"user_id": null,
"flight_info": {
"YU24268": {
"seat": {
"width": 45.72,
"pitch": 73.66
},
"delay": {
"ontime_percent": 0.66666669,
"max": 53,
"mean": 37,
"min": 28
}
},
"delay": {
"ontime_percent": 0.67741936,
"max": 305,
"mean": 33,
"min": 0
}
}
},
"travelpayouts_api_request": true,
"clean_marker": "75089",
"currency": "usd",
"internal": false,
"airports": {
"ORY": {
"rates": "12",
"city_code": "PAR",
"country_code": "FR",
"country": "France",
"time_zone": "Europe/Paris",
"name": "Paris Orly Airport",
"city": "Paris"
},
"SXF": {
"rates": "27",
"city_code": "BER",
"country_code": "DE",
"country": "Germany",
"time_zone": "Europe/Berlin",
"name": "Schonefeld Airport",
"city": "Berlin"
}
}
我使用此代码查找我需要的机场(来自国际航空运输协会代码),但我无法获得这座城市。
function find_city_from_IATA($my_value, $key1)
{
foreach ($key1->airports as $key=>$value) {
echo $key;
echo $my_value;
if ($key==$my_value) {
$city = json_decode($key1->airports,true);
// echo $key1->airlines['U2']->city;
$city = $city->city;
echo $city;
return $city;
}
}
}
如何根据机场IATA获取城市名称? (iata是机场对象拥有的三字母代码密钥)。
答案 0 :(得分:1)
这样的事情:
$airport_code = 'ORY';
// $my_irpost_string is your json string
$data = json_decode($my_json_string, true);
$city = $data['airports'][$airport_code]['city'];
print($city);
您不需要foreach,因为您已经知道代码。这意味着你的foreach +比较只是数组值@ code。
这是一个众所周知的反模式:https://softwareengineering.stackexchange.com/questions/348682/what-is-the-for-case-antipattern