Search a key in a Json (nested array) PHP

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 14:58:33

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

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