Access array key using uasort in PHP

前端 未结 2 1828
抹茶落季
抹茶落季 2020-12-31 13:25

If have a rather basic uasort function in PHP that looks like this:

uasort($arr, function($a, $b) {
                if ($a > $b)
                     


        
相关标签:
2条回答
  • 2020-12-31 14:01

    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;
    });
    
    0 讨论(0)
  • 2020-12-31 14:05
    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.

    0 讨论(0)
提交回复
热议问题