John Smith
John Smith

Reputation: 1290

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'.

Upvotes: 1

Views: 1223

Answers (2)

John Smith
John Smith

Reputation: 1290

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.

Upvotes: 1

Luke Willis
Luke Willis

Reputation: 8580

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'];
});

Upvotes: 1

Related Questions