sort array in DESC order

后端 未结 4 1756
情深已故
情深已故 2020-12-30 07:28

How can i sort this array by arrray key

array(
4 => \'four\',
3 => \'three\',
2 => \'two\',
1 => \'one\',
)

like this



        
4条回答
  •  时光说笑
    2020-12-30 08:17

    You have an array, you want to sort it by keys, in reverse order -- you can use the krsort function :

    Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.


    In you case, you'd have this kind of code :

    $arr = array(
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
    );
    
    krsort($arr);
    var_dump($arr);
    

    which would get you this kind of output :

    $ /usr/local/php-5.3/bin/php temp.php
    array(4) {
      [4]=>
      string(4) "four"
      [3]=>
      string(5) "three"
      [2]=>
      string(3) "two"
      [1]=>
      string(3) "one"
    }
    


    As a sidenode : if you had wanted to sort by values, you could have used arsort -- but it doesn't seem to be what you want, here.

提交回复
热议问题