为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 从 api.met.no 读取天气信息

PHP 从 api.met.no 读取天气信息

PHP
三国纷争 2023-10-15 16:00:46
我正在尝试从此https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=-16.516667&lon=-68.166667读取 JSON$options = array(    'http'=>array(      'method'=>"GET",      'header'=>"Accept-language: en\r\n" .                "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad     ));  $context = stream_context_create($options);$data_url = "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=-16.516667&lon=-68.166667";$json = file_get_contents($data_url,false,$context);$data = new RecursiveIteratorIterator(    new RecursiveArrayIterator(json_decode($json, TRUE)),    RecursiveIteratorIterator::SELF_FIRST);foreach ($data as $key => $val) {    if(is_array($val)) {        echo "$key:\n<br>";    } else {        echo "$key => $val\n<br>";    }}这工作正常,但我需要根据键选择特定值,例如:foreach ($data as $key) {      echo $key["properties"] ["timeseries"] ["0-x"] ["data"] ["instant"] ["details"];}但这当然对我不起作用。请问不知道怎么办?谢谢
查看完整描述

1 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

查看原始 json 返回,您尝试获取的项目相当隐蔽,但您仍然可以轻松获取它。数据返回示例:


{

  "type": "Feature",

  "geometry": {

     ...

  },

  "properties": {

    "meta": {

       ...

    },

    "timeseries": [

        {

        "time": "2020-08-18T12:00:00Z",

        "data": {

          "instant": {

            "details": {

              "air_pressure_at_sea_level": 1018.4,

              "air_temperature": 4.7,

              "cloud_area_fraction": 92.2,

              "relative_humidity": 59.3,

              "wind_from_direction": 308.4,

              "wind_speed": 3.8

            }

         },

    ...


您可以通过以下方式访问该特定数据:


$json = file_get_contents($data_url,false,$context);


// This is all you need to turn json into a usable array

$data = json_decode($json,true); 


// Loop on the nested timeseries group:

foreach($data['properties']['timeseries'] as $ts) {

    

    // the time part of it

    $time    = $ts['time'];

    

    // get at it direct

    $var     = $ts['data']['instant']['details']['air_temperature'];


    // shorthand it if you wish:

    $details = $ts['data']['instant']['details'];

    $var     = $details['air_temperature'];

    

    // do whatever else you need to do with it

    echo $var;

    $array_of_temps[] = $var;

    // etc ...


}


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信