2010-06-23 111 views
2

我想使用scandir显示在特定目录(工作正常)中列出的文件夹的选择列表,但是,我需要它也将子文件夹(如果有的话)添加到我的选择列表中。如果有人能帮助我,那会很棒!使用PHP创建文件夹选择列表 - 包括子文件夹?

这是我想要的结构:

<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

递归遍历它们。 – Andrey 2010-06-23 01:40:28

回答

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; 
} 
+0

谢谢你,但它显示文件也 - 我只想要自己的文件夹:) – SoulieBaby 2010-06-23 02:27:46

+0

啊,我为你修好了:)如果你需要它来显示。和..,在$ scan = scandir后添加以下行: if($ subdir == 0){ echo“”; } – abelito 2010-06-23 03:04:50

+0

再次感谢你,但现在它没有显示任何东西:( – SoulieBaby 2010-06-23 03:16:29

6
//Requires PHP 5.3 
$it = new RecursiveTreeIterator(
    new RecursiveDirectoryIterator($dir)); 

foreach ($it as $k => $v) { 
    echo "<option>".htmlspecialchars($v)."</option>\n"; 
} 

您可以自定义前缀RecursiveTreeIterator::setPrefixPart

0

您可以使用PHP“来代替”功能http://php.net/manual/en/function.glob.php,并建立一个递归函数去无限级深度(即调用自身的函数)。这是短,然后使用 “SCANDIR”

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>'; 

,这将产生完全相同的请求的输出类型。

相关问题