0

I want to sort this key-value array by values first, then keys.

This is the array:

$a = [
    10 => 1,
    4 => 2,
    3 => 2
];

i want to get:

4 => 2,
3 => 2,
10 => 1

I tried to use arsort, but can't get current answer.

deceze
  • 471,072
  • 76
  • 664
  • 811
RryLee
  • 425
  • 3
  • 6

1 Answers1

0

Use uksort to sort by keys, use those keys to look up the values in the array, do a comparison by values first and keys upon equality:

uksort($arr, function ($a, $b) use ($arr) {
    if (($res = $arr[$a] - $arr[$b]) != 0) {
        return $res;
    }
    return $a - $b;
});

See https://stackoverflow.com/a/17364128/476 for more in-depth explanations of sort callbacks.

Community
  • 1
  • 1
deceze
  • 471,072
  • 76
  • 664
  • 811