Categories
Development PHP

Get with PHP Array Tree Values Recursively with start and stop limit level

I am making a module for creating navigation menus and I would like to give the possibility to set an initial and final level. I have this array tree with level how can return it setting a start level and stop level ? this is my function that return empty.

Original Array:

Array
(
    [0] => Array
        (
            [id] => 22
            [pid] => 12
            [level] => 0
            [children] => 
        )

    [1] => Array
        (
            [id] => 24
            [pid] => 12
            [level] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 27
                            [pid] => 24
                            [level] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 28
                                            [pid] => 27
                                            [level] => 2
                                            [children] => 
                                        )

                                )

                        )

                )

        )

    [2] => Array
        (
            [id] => 25
            [pid] => 12
            [level] => 0
            [children] => 
        )

    [3] => Array
        (
            [id] => 26
            [pid] => 12
            [level] => 0
            [children] => 
        )

)

My function:

function get_tree_limit ($pages, $start_level, $stop_level) {

    $result = Array();

    foreach( $pages as $page ) {

        $children = Array();

        if(isset($page['children'])){
            $children = get_tree_limit ($page['children'], $start_level, $stop_level);
        }

        if($page['level'] >= $start_level && $page['level'] <= $stop_level){

            $result[] = Array(
                'id' => $page['id'], 'pid' => $page['pid'], 'level' => $page['level'],
                'children' => $children
            );

        }

    }

    return $result;

}

if I try:

$rpage = get_tree_limit ($pages, 1, 2);
print_r($rpage);

The result is empty:

Array()

Where I am wrong ?

Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *