在Json(嵌套数组)PHP中搜索键 [英] Search a key in a Json (nested array) PHP

查看:80
本文介绍了在Json(嵌套数组)PHP中搜索键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WU api获取每小时的天气数据。 API返回一个具有多个小时值的Json,我想查询我需要的一个:

I use WU api to get some hourly weather data. The API returns a Json with multiple hourly values and I want to query the one that I need:

Json:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "hourly": 1
  }
    }
        ,
    "hourly_forecast": [
        {
        "FCTTIME": {
        "hour": "13","hour_padded": "13","min": "00","min_unpadded": "0","sec": "0","year": "2015","mon": "12","mon_padded": "12","mon_abbrev": "Dec","mday": "30","mday_padded": "30","yday": "363","isdst": "0","epoch": "1451509200","pretty": "1:00 PM PST on December 30, 2015","civil": "1:00 PM","month_name": "December","month_name_abbrev": "Dec","weekday_name": "Wednesday","weekday_name_night": "Wednesday Night","weekday_name_abbrev": "Wed","weekday_name_unlang": "Wednesday","weekday_name_night_unlang": "Wednesday Night","ampm": "PM","tz": "","age": "","UTCDATE": ""
        },
        "temp": {"english": "60", "metric": "16"},
        "dewpoint": {"english": "34", "metric": "1"},
        "condition": "Clear",
        "icon": "clear"
        }
        ,
        {
        "FCTTIME": {
        ...
        }
        ,
        "FCTTIME": {
        ...
        },
        ... more FCTTIME
   ]
}

这是我获取的代码hourly_forecast 作为数组:

$jsonRequest    = file_get_contents("weather.json");
$data           = json_decode($jsonRequest, true);

$array   = @$data['hourly_forecast'];

我需要获取 temp 和< hour的code> condition : 13 。因此,PHP将显示以下内容:天气为$ condition,温度为$ temp。

I need to get the temp and condition for "hour": "13". So the PHP would print something like: The weather is $condition with $temp degree.

推荐答案

您应该能够遍历每小时的预测集,并且当找到与所需小时数相匹配的预测时,从该预测中获取所需的值,然后退出循环。

You should be able to loop over the set of hourly forecasts, and when you find the one that matches the hour you are looking for, get the values you want from that forecast and then break out of the loop.

foreach ($data['hourly_forecast'] as $forecast) {
    if ($forecast['FCTTIME']['hour'] == 13) {
        $condition = $forecast['condition'];
        $temp = $forecast['temp'];
        break;
    }
}

这篇关于在Json(嵌套数组)PHP中搜索键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆