Access array key using uasort in PHP

拈花ヽ惹草 提交于 2019-11-30 09:15:34
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.

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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!