我在php中有一个递归函数,它从数据库中获取一个文件夹树。每个文件夹都有一个id,一个名称和一个父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告诉我们递归函数的嵌套级别,但它不是......它只计算调用次数。我希望很明显,我想知道每个子元素的“代”。
尝试在函数范围之外使用$ indent var,同样,在结束遍历节点(文件夹)内容后,你将返回一个级别,所以在某些时候你应该做一个$ 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控制视觉缩进。这将成为:
$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>';
}
}