我正在尝试使用scandir来显示特定目录中列出的文件夹的选择列表(工作正常)但是,我需要它还将子文件夹(如果有的话)添加到我的选择列表中。如果有人能帮助我,那就太好了!
这是我想要的结构:
<option>folder 1</option>
<option> --child 1</option>
<option> folder 2</option>
<option> folder 3</option>
<option> --child 1</option>
<option> --child 2</option>
<option> --child 3</option>
这是我从这个帖子(Using scandir() to find folders in a directory (PHP))获得的代码(仅显示父文件夹):
$dir = $_SERVER['DOCUMENT_ROOT']."\\folder\\";
$path = $dir;
$results = scandir($path);
$folders = array();
foreach ($results as $result) {
if ($result == '.' || $result == '..') continue;
if (is_dir($path . '/' . $result)) {
$folders[] = $result;
};
};
^^但我需要它来显示子目录..如果有人可以帮助,那就太好了! :)
编辑:忘了说我不想要文件,只有文件夹..
答案 0 :(得分:6)
//Requires PHP 5.3
$it = new RecursiveTreeIterator(
new RecursiveDirectoryIterator($dir));
foreach ($it as $k => $v) {
echo "<option>".htmlspecialchars($v)."</option>\n";
}
您可以使用RecursiveTreeIterator::setPrefixPart
自定义前缀。
答案 1 :(得分:2)
/* FUNCTION: showDir
* DESCRIPTION: Creates a list options from all files, folders, and recursivly
* found files and subfolders. Echos all the options as they are retrieved
* EXAMPLE: showDir(".") */
function showDir( $dir , $subdir = 0 ) {
if ( !is_dir( $dir ) ) { return false; }
$scan = scandir( $dir );
foreach( $scan as $key => $val ) {
if ( $val[0] == "." ) { continue; }
if ( is_dir( $dir . "/" . $val ) ) {
echo "<option>" . str_repeat( "--", $subdir ) . $val . "</option>\n";
if ( $val[0] !="." ) {
showDir( $dir . "/" . $val , $subdir + 1 );
}
}
}
return true;
}
答案 2 :(得分:0)
你可以使用PHP&#34; glob&#34;函数http://php.net/manual/en/function.glob.php,并构建一个递归函数(一个调用自身的函数)来达到无限级别的深度。它比使用&#34; scandir&#34;
短function glob_dir_recursive($dirs, $depth=0) {
foreach ($dirs as $item) {
echo '<option>' . str_repeat('-',$depth*1) . basename($item) . '</option>'; //can use also "basename($item)" or "realpath($item)"
$subdir = glob($item . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR); //use DIRECTORY_SEPARATOR to be OS independent
if (!empty($subdir)) { //if subdir array is not empty make function recursive
glob_dir_recursive($subdir, $depth+1); //execute the function again with current subdir, increment depth
}
}
}
用法:
$dirs = array('galleries'); //relative path examples: 'galleries' or '../galleries' or 'galleries/subfolder'.
//$dirs = array($_SERVER['DOCUMENT_ROOT'].'/galleries'); //absolute path example
//$dirs = array('galleries', $_SERVER['DOCUMENT_ROOT'].'/logs'); //multiple paths example
echo '<select>';
glob_dir_recursive($dirs); //to list directories and files
echo '</select>';
这将生成所请求的输出类型。