简体   繁体   中英

How to sort all levels of multidimensional array by key?

I found this code for sorting:

usort($array, function($a, $b) {
    return $a['order_inside_level'] - $b['order_inside_level'];
});

It's good for one level. I have something like that:

array(
 array(
     'level'=>'aaa',
     'order'='1',
     'subs'=>array(
         array(
             'level'=>'bbb',
             'order'='1',
             'subs'=>array(
                 array(
                     'level'=>'ccc',
                     'order'='1',
                     'subs'=>array(
                         array(
                             'level'=>'ddd',
                             'order'='1',
                             'subs'=>array(
                                 ...
                             )
                         )
                     )
                 )
                 ,
                 array(
                     'level'=>'ccc',
                     'order'='2',
                     'subs'=>array(

                     )
                 )
             ),
         array(
             'level'=>'bbb',
             'order'='2'
         ),
         array(
             'level'=>'bbb',
             'order'='3'
         )
         )
     )
 ),
 array(
     'level'=>'aaa',
     'order'='2',
     'subs'=>array(

     )
 )

 )

Array may have any depth and any number of elements in each level. I need to sort each level of depth (aaa,bbb,ccc, etc) using the code above by key 'order'.

You will need to do this recursively .

recursive_sort($arr, $func) {
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            recursive_sort($val, $func);
        }
    }
    usort($arr, $func);
}

This code will iterate over the given array, and for each value that is an array, call itself with the value. The result is that usort will be called for every array within the structure.

You would call the function the same as you would usort :

recursive_sort($array, function($a, $b) {
    return $a['order_inside_level'] - $b['order_inside_level'];
});
function recursive_sort(&$arr) {
            fs($arr);
        foreach($arr as $k=> &$v){
            if (isset($v['subs'])) {
                 recursive_sort($v['subs']);
             }
        }
}


function sortByOrder($a, $b) {
    return $a['order_inside_level'] - $b['order_inside_level'];
}

function fs(&$array){

    usort($array, 'sortByOrder');

}

After multiple tries I have this. It works. Name of key (subs) is hardcoded what is not so good, but... I am glad it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM