PHP如何在递归函数中计算嵌套调用的级别? [英] PHP How do I calculate level of nested calls in recursive function?
问题描述
我在php中有一个递归函数,该函数从数据库中获取文件夹树.每个文件夹都有一个ID,一个名称和一个父ID.
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();
我希望变量$ indent可以告诉我们递归函数的嵌套程度,但事实并非如此,它只是计算调用次数.我希望很明显,我想知道每个子元素的代".
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.
推荐答案
尝试将$ indent var置于函数范围之外,此外,在结束遍历节点(文件夹)的内容之后,您将返回一个级别,以便在某些时候,您应该使用$ indent-;
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 (' ', $indent).' <a href="filebrowser.php?parent='.$folder['id'].'"> '.$folder['naam'].' </a><br>';
$indent++;
show_subfolders($folder['id']);
$indent--;
}
}
还添加了str_repeat函数,以便在浏览器中呈现链接时缩进"链接.尽管更好的方法是在中绘制链接,这将允许您使用CSS控制视觉缩进.那会做到的:
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>';
}
}
这篇关于PHP如何在递归函数中计算嵌套调用的级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!