The use directive (in the deceze solution) does not work in my old installation of PHP 5.3.1, while this will provide 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 returns a sorted array. And, of course, my โmagicโ when sorting keys is pretty simple. Keys are sorted in the same way as values. By changing the instruction $new[$k]="$v $k"; , you can change the behavior to suit your needs.
as a note ...
The deceze solution will only work on my server 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; });
cars10m
source share