mike
mike

Reputation: 31

PHP How to sort associative array first by keys then by 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 sort like this :

8 => 23
26 => 23
28 => 23
33 => 23
16 => 15
30 => 15
1 => 12
11 => 12
15 => 12
29 => 12

Upvotes: 3

Views: 1922

Answers (3)

salathe
salathe

Reputation: 51970

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);

Upvotes: 4

Awais Qarni
Awais Qarni

Reputation: 18016

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

Upvotes: 0

Rob Agar
Rob Agar

Reputation: 12469

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.

Upvotes: 5

Related Questions