I’m trying to sort an array by value descending keeping keys (arsort), but if the values are equal I want it also sorted in order of keys ascending (ksort).
I’ve been trying this:
ksort($array);
arsort($array);
But the ksort is not kept, and the keys get jumbled up again after the arsort.
E.g. if my input array in:
$array[0] = 4;
$array[1] = 2;
$array[2] = 3;
$array[3] = 1;
$array[4] = 4;
I want to sort it so it ends like this:
$array[0] = 4;
$array[4] = 4;
$array[2] = 3;
$array[1] = 2;
$array[3] = 1;
NOT like this:
$array[4] = 4;
$array[0] = 4;
$array[2] = 3;
$array[1] = 2;
$array[3] = 1;
But the previous order of the keys appears to be disturbed by arsort.
PHP dropped stable sorting (which guaranteed the ordering you wanted) in PHP 4.1:
https://bugs.php.net/bug.php?id=53341&edit=1
Here’s a seemingly dupe question, with a code snippet, to work around it (basically: write your own sort function. Boo.):
Preserve key order (stable sort) when sorting with PHP's uasort