0

It is strange with asort, I want to sort the items in an array by their value,

$items = Array ( "1" => 10 , "11" => 10, "22" => 10 );

// Sort an array and maintain index association.
asort($items);

var_dump($items);

So since all values are the same, then asort shouldn't doing anything (I assume), but the result I get,

array (size=3)
  22 => string '10' (length=2)
  11 => string '10' (length=2)
  1 => string '10' (length=2)

It reverses the order!? Why?

what I want (I think it should be like this),

array (size=3)
  1 => string '10' (length=2)
  11 => string '10' (length=2)
  22 => string '10' (length=2)

Any ideas?

EDIT:

I tried with this below,

// Comparison function
private function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

...

// Sort an array and maintain index association.
uasort($items, array($this, "cmp"));

But I still get the same 'error' result....

Run
  • 54,938
  • 169
  • 450
  • 748
  • 1
    php sorts are not stable, which is why that happens. see here about implementing stable sort in php: http://stackoverflow.com/questions/4353739/preserve-key-order-stable-sort-when-sorting-with-phps-uasort – chiliNUT Feb 28 '15 at 06:14

1 Answers1

1

Since the version 4.1.0 PHP sort is not stable due to sorting algorithm, which cannot take into account both value and key. You have to use your own implementation of comparison considering key in case of equal values. For example you can modify original array values into (key, value) pairs, sort array and transform it into single dimensional back.

$items = ["1" => 10, "11" => 10, "22" => 10];

$callback = function ($a, $b) use ($callback) {
    $result = $a['value'] - $b['value'];

    if ($result == 0) {
        $result = $a['key'] - $b['key'];
    }

    return $result;
};

array_walk($items, function (&$value, $key) {
    $value = ["key" => $key, "value" => $value];
});

usort($items, $callback);

$items = array_combine(array_column($items, 'key'), array_column($items, 'value'));

print_r($items);
Sundrique
  • 627
  • 1
  • 9
  • 14
  • 1
    `uasort` is not going to work, either. [The manual says](http://php.net/manual/en/function.uasort.php): *If two members compare as equal, their relative order in the sorted array is undefined.* This is what makes any of PHP's built in sorting functions a non-stable sort. Although, using the custom `stable_uasort` function in the link you provided looks promising. – Mark Miller Feb 28 '15 at 06:44
  • 1
    Yes, my fault, sorry. Thought uasort allows to consider keys as well. – Sundrique Feb 28 '15 at 07:47
  • 1
    @tealou You can transform original array before sorting and transform it back after, see updated answer. Or write you own implementation of quicksort or mergesort algorithm taking keys into account. – Sundrique Feb 28 '15 at 09:27