1

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?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Ash
  • 85
  • 2
  • 10
  • I think array_filter could be of help: http://php.net/manual/en/function.array-filter.php – Mariella Aug 25 '16 at 13:23
  • 1
    I don't know where the data comes from but if it is possible, you should get the right data from there. – jeroen Aug 25 '16 at 13:27

2 Answers2

3

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.

Community
  • 1
  • 1
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

Create a function that loops through the array.

function clearOldPaydates($array)
{
    $cleaned = array();
    foreach($array as $item)
    {
        // if it's the first item of this date we keep it
        // if there is already an item with this date we only overwrite it if it's older
        if(!isset($cleaned[$item['paydate']])
            || strtotime($item['paydate']] > $cleaned[$item['paydate'])
        {
            $cleaned[$item['paydate']] = $item;
        }
    }
    // we return the array with numeric keys
    return array_values($cleaned);
}