If have a rather basic uasort
function in PHP that looks like this:
uasort($arr, function($a, $b) {
if ($a > $b)
The use
directive (in deceze's solution) does not work in my old PHP 5.3.1 installation, while this will deliver the result:
$arr=array('1642'=>1,'9314'=>2,'1634'=>1,'1633'=>5,'1636'=>7,'1610'=>1);
print_r($arr);
function mycmp($a, $b) {
if ($a > $b) return -1;
if ($a < $b) return 1;
else return 0;
}
function mysrt($arr){
foreach ($arr as $k => $v) $new[$k]="$v $k";
uasort($new, 'mycmp'); $ret=array();
foreach ($new as $k => $v) $ret[$k]=$arr[$k];
return $ret;
}
print_r(mysrt($arr));
mysrt()
does not sort 'in-place' but will return the sorted array. And of course: my "magic" on the key sorting is rather basic. Keys will get sorted in the same way as the values. By modifying the statement $new[$k]="$v $k";
you can change the behaviour to suit your needs.
as a side note ...
deceze's solution will work on my server only when I use use(&$arr)
instead of use($arr)
:
uksort($arr, function ($a, $b) use(&$arr) {
return $arr[$a] - $arr[$b] ? $arr[$a] - $arr[$b] : $a - $b;
});
uksort($arr, function ($a, $b) use ($arr) {
return $arr[$a] - $arr[$b] ?: $a - $b;
});
You can get the values by the keys, so use uksort
which gives you the keys. Replace $a - $b
with your appropriate magic, here it's just sorting by the key's value.