Reputation: 31
$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
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
Reputation: 18016
Its quite easy. First use ksort and then use asort for the new sorted array. You will find your result.
Upvotes: 0