Alasdair
Alasdair

Reputation: 14131

PHP combining arsort & ksort

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.

Upvotes: 2

Views: 1514

Answers (2)

Alasdair
Alasdair

Reputation: 14131

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;
    }

Upvotes: 0

James
James

Reputation: 8586

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

Upvotes: 1

Related Questions