3
$arr =array(
    28 => 23,
    26 => 23,
    15 => 12,
    29 => 12,
    1 => 12,
    16 => 15,
    30 => 15,
    11 => 12,
    8 => 23,
    33 => 23
);

how to sort like this :

8 => 23
26 => 23
28 => 23
33 => 23
16 => 15
30 => 15
1 => 12
11 => 12
15 => 12
29 => 12
3
  • Your array is simply sorted by value, yes? Commented Mar 21, 2011 at 12:58
  • You have to write your function and use it as uksort() callback Commented Mar 21, 2011 at 13:04
  • I've merged your two accounts together. Please read this Faq entry about cookie-based accounts. Also, StackOverflow isn't a forum; if you have a new question, please ask a new question. If you want to include more information in your question, please edit it. If you want to interact with one of the people who has answered, you can leave them a comment. Commented Mar 21, 2011 at 16:03

3 Answers 3

5

Use uksort, but make the array available to the comparison function for the secondary comparison by value. Making it a global variable would be the quickest + dirtiest way.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution. Using a closure and passing a copy of the array in with use would be nice... Note you would actually have to pass the array to a different variable before passing it to the closure.
4

You could use uksort() which enables the custom callback to take a look at both the keys and, indirectly, their associated values. Then it's a simple matter of deciding which comparisons to make and returning the appropriate greater-than-less-then-or-zero value to influence the sort order.

Here's an example using a closure around a temporary variable (see Jacob's comment) which should hopefully make sense.

$temp = $arr;
uksort($arr, function ($a,$b) use ($temp) {
    // Same values, sort by key ascending
    if ($temp[$a] === $temp[$b]) {
        return $a - $b;
    }
    // Different values, sort by value descending
    return $temp[$b] - $temp[$a];
});
unset($temp);
print_r($arr);

Comments

0

Its quite easy. First use ksort and then use asort for the new sorted array. You will find your result.

4 Comments

PHP's array sorting functions use quicksort which is unstable. So this can't be guaranteed.
@Jacob. Sorry dude I didnt understand your point. please explain me and correct me...
see Stability. In quicksort if two elements are equal they won't be guaranteed to maintain their original order.
@Jacob, I believe it's OK in this case, as there will be no equal items - each array element has unique key, which is taken into consideration in mike's case.

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.