phparrayssortingarrayofarrays

compare an ID in array of arrays and take only a single row with the date in desc order in PHP


I have an array like this :

$data = array (
  0 => 
  array (
    'UserID' => '1',
    'ShipPinCode' => '411008',
    'createdDate' => '2011-10-04 01:16:54.723',
    'Amount' => '1000.00',
  ),
  1 => 
  array (
    'UserID' => '1',
    'ShipPinCode' => '411008',
    'createdDate' => '2011-10-04 01:24:24.243',
    'Amount' => '1000.00',
  ),
  2 => 
  array (
    'UserID' => '102818',
    'ShipPinCode' => '500072',
    'createdDate' => '2011-11-29 12:17:43.880',
    'Amount' => '2000.00',
  ),
  3 => 
  array (
    'UserID' => '100001',
    'ShipPinCode' => '500072',
    'createdDate' => '2011-11-26 11:49:17.760',
    'Amount' => '2000.00',
  ),
);

I want to sort it in such a way that for duplicate entries of UserID the final output should contain only a single row for that UserID where the createdDate is the largest i.e in descending order.

Desired output :

array (
      0 => 
      array (
        'UserID' => '1',
        'ShipPinCode' => '411008',
        'createdDate' => '2011-10-04 01:24:24.243', //only took one row of UserID 1 where the createdDate is the largest.
        'Amount' => '1000.00',
      ),
      1 => 
      array (
        'UserID' => '102818',
        'ShipPinCode' => '500072',
        'createdDate' => '2011-11-29 12:17:43.880',
        'Amount' => '2000.00',
      ),
      2 => 
      array (
        'UserID' => '100001',
        'ShipPinCode' => '500072',
        'createdDate' => '2011-11-26 11:49:17.760',
        'Amount' => '2000.00',
      ),
    );

I'm not able to figure out how to do the comparison in such a case. How do I do it?


Solution

  • You can sort ascending by the createdDate:

    array_multisort(array_column($data, 'createdDate'), SORT_ASC, $data);
    

    Then you can extract and index on UserID which will only keep the last one:

    $result = array_column($data, null, 'UserID');
    

    If you want to reindex (not needed):

    $result = array_values($result);