Ash Ash - 3 months ago 10
PHP Question

How can I filter an array to include only the most recent items for each id?

I have an array like below:

Array
(
[0] => Array
(
[clearing] => 160000
[paydate] => 2016-08-03
[latecharge] => 900
)
[1] => Array
(
[clearing] => 160000
[paydate] => 2016-08-04
[latecharge] => 950
)
[2] => Array
(
[clearing] => 160001
[paydate] => 2016-08-05
[latecharge] => 850
)
)


I am trying to keep the latest
paydate
of each clearing and remove the rest of the array.

For example, for clearing 160000, the latest
paydate
is 2016-08-04 and for 160001 the latest
paydate
is 2016-08-05 so my result array should be like below:

Array
(
[1] => Array
(
[clearing] => 160000
[paydate] => 2016-08-04
[latecharge] => 950
)
[2] => Array
(
[clearing] => 160001
[paydate] => 2016-08-05
[latecharge] => 850
)
)


How can I do this?

Answer

Loop over your array and group by the 'clearing' key. Each time you get to one where that 'clearing' is not set in your result array, set it to the current instance, or if it is set, replace it if the current instance is newer.

foreach ($clearings as $clearing) {
    $id = $clearing['clearing'];
    if (!isset($latest[$id]) || $latest[$id]['paydate'] < $clearing['paydate']) {
        $latest[$id] = $clearing;
    }
}

The comment from @jeroen makes a good point. If you (or future readers) are getting this array from a database, for example, it will most likely be more efficient to modify your query and do this in the db. The concept is called groupwise maximum, and there are some good answers with a few different ways to get it on this question.

Comments