亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號