将最大递归级别传递给函数。通过这种方式,您可以在运行时决定要深入多少级。
此外,在外部完成“我想要或不想要目录”的决定并作为参数传递是一个好主意(我认为)。这样一个功能可以同时做这两个。
最后,使用函数输出 HTML 几乎不是一个好主意。最好将其作为字符串返回,这样您就可以更自由地移动代码。理想情况下,您希望将所有逻辑与您的演示视图分开(不仅如此;谷歌“MVC”)。
更好的方法是将 HTML模板传递给mkmap
函数并让它使用它来创建 HTML 片段。这样,如果在一个地方你想要 a<ul>
而在另一个地方 a <ul id="another-tree" class="fancy">
,你不需要使用同一个函数的两个版本;但这可能是矫枉过正(str_replace
如果你需要的话,你可以使用 , 或 XML 函数轻松地做到这一点)。
function mkmap($dir, $depth = 1, $only_dirs = True){
$response = '<ul>';
$folder = opendir ($dir);
while ($file = readdir ($folder)) {
if ($file != '.' && $file != '..') {
$pathfile = $dir.'/'.$file;
if ($only_dirs && !is_dir($pathfile))
continue;
$response .= "<li><a href=\"$pathfile\">$file</a></li>";
if (is_dir($pathfile) && ($depth !== 0))
$response .= mkmap($file, $depth - 1, $only_dirs);
}
}
closedir ($folder);
$response .= '</ul>';
return $response;
}
// Reach depth 5
echo mkmap('Main Dir', 5, True);
// The explicit check for depth to be different from zero means
// that if you start with a depth of -1, it will behave as "infinite depth",
// which might be desirable in some use cases.
模板
有很多方法可以模板化函数,但最简单的可能是这样(为了更精细的定制,XML 是强制性的 - 使用字符串函数管理 HTML 具有令人讨厌的时空连续体含义):
function mkmap($dir, $depth = 1, $only_dirs = True,
$template = False) {
if (False === $template) {
$template = array('<ul>','<li><a href="{path}">{file}</a></li>','</ul>');
}
$response = '';
$folder = opendir ($dir);
while ($file = readdir ($folder)) {
if ($file != '.' && $file != '..') {
$pathfile = $dir.'/'.$file;
if ($only_dirs && !is_dir($pathfile))
continue;
$response .= str_replace(array('{path}','{file}'), array($pathfile, $file), $template[1]);
if (is_dir($pathfile) && ($depth !== 0))
$response .= mkmap($file, $depth - 1, $only_dirs, $template);
}
}
closedir ($folder);
return $template[0] . $response . $template[2];
}
该函数像以前一样工作,但您可以传递一个进一步的参数来自定义它:
echo mkmap('Main Dir', 5, True, array(
'<ul class="filetree">',
'<li><a href="{path}"><img src="file.png" /><tt>{file}</tt></a></li>',
'</ul>'));