简体   繁体   中英

PHP How do I calculate level of nested calls in recursive function?

I have a recursive function in php which gets from a database a folder tree. Each folder has an id, a name and a parent id.

function show_subfolders($parent=0, $indent=0) {
    $indent++;
    $folders = sql_to_assoc("SELECT * FROM `folders` WHERE 'parent' = ".$parent.";");
    foreach($folders as $folder) {
        echo ' <a href="filebrowser.php?parent='.$folder['id'].'"> '.$folder['naam'].' </a><br>';
        show_subfolders($folder['id'], $indent);
    }
}

show_subfolders();

I expect that the variable $indent tells us the level of nestedness of the recursive function, but it is not.. it just counts the number of calls. I hope it is clear that I want to know the 'generation' of each child-element.

Try taking the $indent var outside of the function scope, also, after you end traversing a node(folder) contents, you are going back up a level so at some point you should do a $indent--;

$indent = 0;

function show_subfolders(){
    // give this function access to $indent
    //you could also use a class var $this->indent if you make this into a class method
    global $indent;

    $folders = sql_to_assoc("SELECT * FROM `folders` WHERE 'parent' = ".$parent.";");
    foreach($folders as $folder) {
        echo str_repeat ('&nbsp;', $indent).' <a href="filebrowser.php?parent='.$folder['id'].'"> '.$folder['naam'].' </a><br>';
        $indent++;
        show_subfolders($folder['id']);
        $indent--;
    }
}

Also added the str_repeat function so that your links are 'indented' when rendered in the browser. Although a better approach would be to draw the links in a which will allow you to control the visual indentation with css. That would make it:

$indent = 0;

function show_subfolders(){
    // give this function access to $indent
    //you could also use a class var $this->indent if you make this into a class method
    global $indent;

    $folders = sql_to_assoc("SELECT * FROM `folders` WHERE 'parent' = ".$parent.";");
    if (count($folders)){
        echo '<ul>';
        foreach($folders as $folder) {
            echo '<li><a href="filebrowser.php?parent='.$folder['id'].'"> '.$folder['naam'].' </a></li>';
            $indent++;
            show_subfolders($folder['id']);
            $indent--;
        }
        echo '</ul>';
    }
}

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