Sort multidimensional array alphabetically

后端 未结 4 644
予麋鹿
予麋鹿 2020-12-07 02:29

How can I sort a array like this alphabetically:

$allowed = array(
  \'pre\'    => array(),
  \'code\'   => array(),
  \'a\'      => array(
                 


        
相关标签:
4条回答
  • 2020-12-07 02:57

    Aha! You need uksort();

    Comparison of PHP sorting functions. (dam useful)

    Edit: Reason is, you seem to want to sort inside arrays as well? AFAIK ksort by itself doesn't do that - it outright ignores the value of the original array.

    Edit2: This ought to work (though uses recursion instead of kusort):

    function ksort_deep(&$array){
        ksort($array);
        foreach($array as &$value)
            if(is_array($value))
                ksort_deep($value);
    }
    
    // example of use:
    ksort_deep($allowed);
    
    // see it in action
    echo '<pre>'.print_r($allowed,true).'</pre>';
    

    Important: As a side effect of not using uksort() if the same array references to itself, you get an infinite loop. This won't happen in normal cases, but you never know :)

    0 讨论(0)
  • 2020-12-07 03:11

    ksort() ?

    0 讨论(0)
  • 2020-12-07 03:13

    You use

    ksort($allowed);
    

    http://php.net/manual/en/function.ksort.php

    0 讨论(0)
  • 2020-12-07 03:19
    bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
    

    as described here. The 'See Also' section is usually very helpful

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