Order multidimensional array recursively at each level in PHP

前端 未结 3 1603
感情败类
感情败类 2020-12-03 21:35

I have an array of this form:

Array
(
    [first_level] => Array
        (
            [dir_3] => Array
                (
                    [subdir_1         


        
相关标签:
3条回答
  • 2020-12-03 22:00
    function ksort_recursive(&$array)
    {
        if (is_array($array)) {
            ksort($array);
            array_walk($array, 'ksort_recursive');
        }
    }
    

    As noted in their comments, answers with return ksort() are incorrect as ksort() returns a success bool.

    Note that this function does not throw "Warning: ksort() expects parameter 1 to be array" when given a non-array - this matches my requirements but perhaps not yours.

    0 讨论(0)
  • 2020-12-03 22:06

    You need to use ksort.

    // Not tested ...    
    function recursive_ksort(&$array) {
        foreach ($array as $k => &$v) {
            if (is_array($v)) {
                recursive_ksort($v);
            }
        }
        return ksort($array);
    }
    
    0 讨论(0)
  • 2020-12-03 22:17

    Use a recursive function:

    // Note this method returns a boolean and not the array
    function recur_ksort(&$array) {
       foreach ($array as &$value) {
          if (is_array($value)) recur_ksort($value);
       }
       return ksort($array);
    }
    
    0 讨论(0)
提交回复
热议问题