2

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Alasdair
  • 13,348
  • 18
  • 82
  • 138
  • possible duplicate of [Preserve key order (stable sort) when sorting with PHP's uasort](http://stackoverflow.com/questions/4353739/preserve-key-order-stable-sort-when-sorting-with-phps-uasort) – outis Nov 28 '11 at 07:47

2 Answers2

1

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

Community
  • 1
  • 1
James
  • 8,512
  • 1
  • 26
  • 28
0

That's a pity, since it's not supported, here's a function I wrote for it:

function arksort($array)
    {
    arsort($array);
    $newarray=array();
    $temp=array();
    $on=current($array);
    foreach($array as $key => $val)
        {
        if ($val===$on) $temp[$key]=$val;
        else
            {
            ksort($temp);
            $newarray=$newarray+$temp;
            $temp=array();
            $on=$val;
            $temp[$key]=$val;
            }
        }
    ksort($temp);
    $newarray=$newarray+$temp;
    reset($newarray);
    return $newarray;
    }
Alasdair
  • 13,348
  • 18
  • 82
  • 138