[英]PHP How do I calculate level of nested calls in recursive function?
我在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>';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.