Search a key in a Json (nested array) PHP

ぐ巨炮叔叔 提交于 2019-12-08 04:02:22

问题


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
   ]
}

This is my code to get hourly_forecast as array:

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

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

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.


回答1:


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;
    }
}



回答2:


First dont convert an object to an array, there is no need to.

So change $data = json_decode($jsonRequest, true);

To $data = json_decode($jsonRequest);

Then loop over the $data->hourly_forecast array looking for the specific time you need like this

foreach( $data->hourly_forecast as $forecast ) {
    if ( $forecast->FCTTIME->hour == 13 ) {
        echo 'The time  ' . $forecast->FCTTIME->hour.PHP_EOL;
        echo 'The temp F' . $forecast->temp->english.PHP_EOL;
        echo 'The temp C' . $forecast->temp->metric.PHP_EOL;
        echo 'The condition ' . $forecast->condition.PHP_EOL;

        // if this is all you need, stop looping
        break;
    }
}


来源:https://stackoverflow.com/questions/34537356/search-a-key-in-a-json-nested-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!