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....

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

uasort is not going to work, either. The manual says: 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.
Yes, my fault, sorry. Thought uasort allows to consider keys as well.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.