PHP How do I sort an associative array with keys first and then values?

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

how to do it:

8 => 23
26 => 23
28 => 23
33 => 23
16 => 15
30 => 15
1 => 12
11 => 12
15 => 12
29 => 12
+3
source share
3 answers

Use uksort , but create an array available for the comparison function for secondary comparison by value. Making it a global variable would be the fastest and most dirty way.

+5
source

You can use uksort()one that allows a custom callback to look at both keys and, indirectly, their associated values. Then it’s easy to decide which comparisons to make and return the corresponding value of greater than-less-than-or-zero to influence the sorting order.

(. ), , , .

$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);
+4

This is pretty easy. First use ksort and then use asort for the new sorted array. You will find your result.

0
source

All Articles