Php, How do I choose the arrays with the weather exactly at today's date?

I get an array of this kind:

Array
      (
     [0] => Array
(
    [dt] => 1523728800
    [main] => Array
        (
            [temp] => 16.84
            [temp_min] => 15.73
            [temp_max] => 16.84
            [pressure] => 1001.67
            [sea_level] => 1036.08
            [grnd_level] => 1001.67
            [humidity] => 66
            [temp_kf] => 1.11
        )

    [weather] => Array
        (
            [0] => Array
                (
                    [id] => 800
                    [main] => Clear
                    [description] => clear sky
                    [icon] => 01n
                )

        )


    [dt_txt] => 2018-04-14 18:00:00
)

[1] => Array
    (
        [dt] => 1523739600
        [main] => Array
            (
                [temp] => 12.97
                [temp_min] => 12.23
                [temp_max] => 12.97
                [pressure] => 1002.14
                [sea_level] => 1036.93
                [grnd_level] => 1002.14
                [humidity] => 67
                [temp_kf] => 0.74
            )

        [weather] => Array
            (
                [0] => Array
                    (
                        [id] => 800
                        [main] => Clear
                        [description] => clear sky
                        [icon] => 01n
                    )

            )

        [dt_txt] => 2018-04-14 21:00:00
    )

And there are 36 more. For 8 arrays with the weather for each day with a step of 3 hours.

How do I choose the arrays with the weather exactly at today's date? As you can see, the date is returned - dt_txt, but how do I search it correctly?

2 answers

  • answered 2018-04-14 15:59 Mehdi

    You can loop through the array and check using the unix time given:

    $today_weather = array();
    $today = date('Ymd');
    foreach($data as $weather){
        // Check if the date is today
        if($today === date('Ymd', $weather['dt'])){
            $today_weather[] = $weather;
        }
    }
    

    Edit: This will add today's weather to $today_weather

  • answered 2018-04-14 18:30 Andreas

    You can easily use the 'dt' item in the array and compare it against the range of Unix seconds during this day.

    $daystart = strtotime(date("Y-m-d 00:00:00"));
    $dayend = strtotime(date("Y-m-d 23:59:59"));
    Foreach($arr as $val){
        If($val['dt'] >= $daystart && $val['dt'] <= $dayend){
            $res[] = $val;
        }
    }
    Var_dump($res);
    

    I created a smaller similar array like yours to simulate the use.
    https://3v4l.org/kedRX