Цикл только в течение 5 дней, а не почасовая открытая погода. - PullRequest
0 голосов
/ 07 марта 2019

Я пытаюсь отобразить данные из открытого погодного API, и я успешно использовал API и вывел некоторые данные из него.Однако API, который я использую, дает мне почасовые данные.Но мне нужен только первый набор данных за все 5 дней в ответе API.

Я перебрал все поля, которые хочу, но он дает мне каждое поле за последние 3 часа.Я хочу только поля на 5 дней.(Это должно дать мне 5 результатов, но дает мне результаты ежечасно за все 5 дней)

Поэтому мой вопрос заключается в том, как получить результаты за 5 дней только за циклическим ответом API, вместо того, чтобы получать все из него ежечасно?Вот мой код:

$currentjson_string = file_get_contents("https://api.openweathermap.org/data/2.5/weather?q=Shanghai&appid=&units=imperial");
$forecastjson_string = file_get_contents("https://api.openweathermap.org/data/2.5/forecast?q=Shanghai&appid=&units=imperial");

$currentParsed = json_decode($currentjson_string, true);
$forecastParsed = json_decode($forecastjson_string, true);


// City Variables

$country = $currentParsed['name'];
$city = $currentParsed['sys']['country'];

// Current Weather Variables

$currentWeatherLongitude = $currentParsed['coord']['lon'];
$currentWeatherLatitude = $currentParsed['coord']['lat'];
$currentIcon = $currentParsed['weather'][0]['icon'];
$currentWeatherF = $currentParsed['main']['temp'];
$currentWeatherconditions = $currentParsed['weather'][0]['description'];
// F to C
$currentWeatherC = ($currentWeatherF - 32) * 5 / 9;
$currentWeathermin = $currentParsed['main']['temp_min'];
$currentWeathermax = $currentParsed['main']['temp_max'];

<div class="weather-info">
<div class="weather-centered-box">
<span class="weather-description" style="font-size:40px;"><center><?php echo $country . ', ' . $city ?></center></span>
<span class="current-conditions">Current Conditions</span> 
<span class="weather-conditions"><center><?php echo ucwords($currentWeatherconditions) ?></center></span>
<span class="weather-location" style="font-size:24px;"><?php echo 'Latitude ' . $currentWeatherLatitude . ', Longitude ' . $currentWeatherLongitude ?></span>
<span class="weather-icon"><center><?php echo '<img src="http://openweathermap.org/img/w/'.$currentIcon.'.png" />'; ?></center></span>

<?php

echo '<span class="weather-temp-f">'.$currentWeatherF.' <sup>&deg;</sup>F ('.round($currentWeatherC, 2).' <sup>&deg;</sup>C)</span>';

foreach ($forecastParsed['list'] as $key) {
  

// This is where im stuck. I don't want all the temperatures only 5 days worth of results from the temperature not hourly?
 echo $key['main']['temp'];

?>

JSON Ответ от API:

{
    "cod": "200",
    "message": 0.0042,
    "cnt": 39,
    "list": [
        {
            "dt": 1551927600,
            "main": {
                "temp": 53.04,
                "temp_min": 51.65,
                "temp_max": 53.04,
                "pressure": 1027.25,
                "sea_level": 1027.25,
                "grnd_level": 1026.28,
                "humidity": 64,
                "temp_kf": 0.77
            },
            "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "02d"
                }
            ],
            "clouds": {
                "all": 8
            },
            "wind": {
                "speed": 15.59,
                "deg": 18.5008
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2019-03-07 03:00:00"
        },
        {
            "dt": 1551938400,
            "main": {
                "temp": 54.28,
                "temp_min": 53.24,
                "temp_max": 54.28,
                "pressure": 1026.29,
                "sea_level": 1026.29,
                "grnd_level": 1025.32,
                "humidity": 56,
                "temp_kf": 0.58
            },
            "weather": [
                {
                    "id": 801,
                    "main": "Clouds",
                    "description": "few clouds",
                    "icon": "02d"
                }
            ],
            "clouds": {
                "all": 20
            },
            "wind": {
                "speed": 13.56,
                "deg": 20.0005
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2019-03-07 06:00:00"
        },
        {
            "dt": 1551949200,
            "main": {
                "temp": 49.8,
                "temp_min": 49.11,
                "temp_max": 49.8,
                "pressure": 1026.22,
                "sea_level": 1026.22,
                "grnd_level": 1025.34,
                "humidity": 54,
                "temp_kf": 0.39
            },
            "weather": [
                {
                    "id": 803,
                    "main": "Clouds",
                    "description": "broken clouds",
                    "icon": "04d"
                }
            ],
            "clouds": {
                "all": 64
            },
            "wind": {
                "speed": 11.74,
                "deg": 28.0067
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2019-03-07 09:00:00"
        },
        {
            "dt": 1551960000,
            "main": {
                "temp": 41.05,
                "temp_min": 40.71,
                "temp_max": 41.05,
                "pressure": 1027,
                "sea_level": 1027,
                "grnd_level": 1026.12,
                "humidity": 70,
                "temp_kf": 0.19
            },
            "weather": [
                {
                    "id": 801,
                    "main": "Clouds",
                    "description": "few clouds",
                    "icon": "02n"
                }
            ],
            "clouds": {
                "all": 24
            },
            "wind": {
                "speed": 9.89,
                "deg": 38.5044
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2019-03-07 12:00:00"
        },
        {
            "dt": 1551970800,
            "main": {
                "temp": 35.75,
                "temp_min": 35.75,
                "temp_max": 35.75,
                "pressure": 1027.53,
                "sea_level": 1027.53,
                "grnd_level": 1026.67,
                "humidity": 90,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 802,
                    "main": "Clouds",
                    "description": "scattered clouds",
                    "icon": "03n"
                }
            ],
            "clouds": {
                "all": 48
            },
            "wind": {
                "speed": 6.4,
                "deg": 26.001
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2019-03-07 15:00:00"
        },
        {
            "dt": 1551981600,
            "main": {
                "temp": 34.54,
                "temp_min": 34.54,
                "temp_max": 34.54,
                "pressure": 1026.13,
                "sea_level": 1026.13,
                "grnd_level": 1025.29,
                "humidity": 94,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 803,
                    "main": "Clouds",
                    "description": "broken clouds",
                    "icon": "04n"
                }
            ],
            "clouds": {
                "all": 64
            },
            "wind": {
                "speed": 3.62,
                "deg": 25.0002
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2019-03-07 18:00:00"
        },
        {
            "dt": 1551992400,
            "main": {
                "temp": 34.49,
                "temp_min": 34.49,
                "temp_max": 34.49,
                "pressure": 1025.72,
                "sea_level": 1025.72,
                "grnd_level": 1024.85,
                "humidity": 92,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 804,
                    "main": "Clouds",
                    "description": "overcast clouds",
                    "icon": "04n"
                }
            ],
            "clouds": {
                "all": 88
            },
            "wind": {
                "speed": 3.38,
                "deg": 31.0012
            },
            "sys": {
                "pod": "n"
            },
            "dt_txt": "2019-03-07 21:00:00"
        },
        {
            "dt": 1552003200,
            "main": {
                "temp": 42.85,
                "temp_min": 42.85,
                "temp_max": 42.85,
                "pressure": 1026.72,
                "sea_level": 1026.72,
                "grnd_level": 1025.83,
                "humidity": 86,
                "temp_kf": 0
            },
            "weather": [
                {
                    "id": 804,
                    "main": "Clouds",
                    "description": "overcast clouds",
                    "icon": "04d"
                }
            ],
            "clouds": {
                "all": 88
            },
            "wind": {
                "speed": 7.49,
                "deg": 72.5035
            },
            "sys": {
                "pod": "d"
            },
            "dt_txt": "2019-03-08 00:00:00"
        }

1 Ответ

1 голос
/ 07 марта 2019

Вы можете попробовать что-то вроде этого. Может быть необходимо изменить приведенный ниже код, так как он не протестирован, но он дает вам представление о том, как решить эту проблему:

$previous_date = '';
foreach ($forecastParsed['list'] as $key) {
   $dt_txt = $key['dt_txt'];
   $date = new DateTime($dt_txt);
   $current_date = $date->format('Y-m-d');
   if ($current_date != $previous_date) { echo $key['main']['temp']; }
   $previous_date = $current_date;
}

Его также можно записать более кратко (т. Е. Объединить первые 2 строки в foreach, чтобы исключить переменную $dt_txt).

Объяснение логики:
Этот цикл foreach получает дату и время для текущего $key, удаляет временную метку и помещает ее в $current_date. Тогда $current_date сравнивается с $previous_date. Если они не совпадают, то мы знаем, что это новый день, и темп повторяется. $previous_date сбрасывается на $current_date, поэтому значение в этой переменной готово к следующему циклу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...