从json访问php对象

从json访问php对象,php,json,Php,Json,我有一个来自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

我有一个来自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"
  }
}
$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);
我用这个代码找到我需要的机场(来自IATA代码),但我无法找到城市

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是机场对象拥有的三字母代码键)。

类似于:

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


这是一个众所周知的反模式:

您不需要使用
json\u decode
,它已经被解码了。您只需要
$value->city
就可以了,这比在整个集合上循环要好得多:)