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