GePu
GePu

Reputation: 320

sort out a specific time of an array in PHP

I need to get the latest time from a specific day. In this example from a friday. I have an array called $arrayFriday which inherits timestamps. Now i need to sort out which timestamps are the latest at the same day.

Array $arrayFriday:

Array
(
    [0] => 1483691580
    [1] => 1483696140
    [2] => 1483701240
    [3] => 1483720920
    [4] => 1489142460
    [5] => 1489144140
    [6] => 1489150260
    [7] => 1489750920
    [8] => 1489760160
    [9] => 1489765800
    [etc.]
)

In this array there are times which i worked up to. e.g. 06.01.2017 17:42 was the time i came home.

The output (from this example) should be:

Array
(
    [0] => 1483720920
    [1] => 1489150260
    [2] => 1489765800
)

Or if i echo it from $integerFriday (GMT+1):

06.01.2017 17:42
10.03.2017 13:51
17.03.2017 16:50

So the output is also an array, but only with sorted out the latest timestamp of the same day.

My try:

foreach ($arrayFriday as $key => $value) {
    if(date('m.d.Y', $value) == date('m.d.Y', $arrayFriday[$key-1])){
        $integerFriday= $value;
    } else {
        echo date('l d.m.Y H:i', $integerFriday);
    } 
}

Upvotes: 1

Views: 98

Answers (2)

Andre S.
Andre S.

Reputation: 2682

Something like this is short and sweet:

rsort($arrayFriday);
$integerFriday = [$arrayFriday[0]];

foreach ($arrayFriday as $time) {
    if(date('m.d.Y', end($integerFriday)) > date('m.d.Y', $time)){
        $integerFriday[] = $time;
    }
}

Of course, the bigger the list, the longer this will take, since you're sorting it. If it's always sorted, then you can just reverse it with array_reverse().

Output:

Friday 17.03.2017 15:50
Friday 10.03.2017 12:51
Friday 06.01.2017 16:42

Upvotes: 0

Don't Panic
Don't Panic

Reputation: 41810

Use the date as the key in your result array. If your array of timestamps is sorted, then this is all you need to do. Subsequent values for the same date will overwrite the value at that date key as you iterate the timestamps, and you'll be left with the greatest timestamp for each date.

foreach ($timestamps as $ts) {
    $latest_times[date('Ymd', $ts)] = $ts;
}

Your array must be sorted beforehand for this to work. It looks like yours is, but if it isn't, then sort($timestamps); first.

Upvotes: 3

Related Questions