-1

How to sort array by preserving key

 $arr = array(strong text
    'a' => array('date' => time() - 1000),
    'b' => array('date' => time() - 2000),
    'c' => array('date' => time() - 3000),
);

I want to sort according to the time().

NIlesh Sharma
  • 4,997
  • 6
  • 30
  • 50
Yanks
  • 161
  • 2
  • 15

2 Answers2

0
function cmp($a, $b)
{
   if($a["date"] == $b["date"]) return 0;

   return($a["date"] >  $b["date"]) ? 1 : -1;
}

usort($array, "cmp");
Daniel Krom
  • 8,637
  • 3
  • 36
  • 39
0

There is a couple of PHP functions that sort arrays - you can see the overview here: http://php.net/manual/en/array.sorting.php

As you want to neither by key nor value, but by some custom logic of yours, you need to use one of the functions starting with u. Ouf of those 3 functions, 2 can be used to sort by value: usort and uasort. The difference between them is that while the first one doesn't preserve the key-value associations, the second one does, which makes uasort the function you need.

uasort takes 2 parameters - an array to be sorted and a callback, that for 2 given elements should return -1, 0 or 1 if the first element is smaller, equal or larger than the second.

In your case, this will work:

print_r($arr);

uasort($arr, function($e1, $e2) {
  if ($e1['date'] == $e2['date']) {
    return 0;
  }
  return ($e1['date'] < $e2['date']) ? -1 : 1;
});

print_r($arr);

Notice: make sure you don't assign the result of uasort to your $arr - the return value of this function is not the sorted array, but a boolean saying if sorting succeeded.

jedrzej.kurylo
  • 34,427
  • 9
  • 81
  • 93