PHP - 在下拉菜单中递归列出所有目录和子目录 [英] PHP - Listing all directories and sub-directories recursively in drop down menu

查看:38
本文介绍了PHP - 在下拉菜单中递归列出所有目录和子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
PHP 获取给定目录的所有子目录

我想要一个下拉菜单来显示 ./files/$userid/ 中的所有子目录,而不仅仅是主文件夹.例如:/files/$userid/folder1/folder2/

I want a drop down menu to show all sub-directories in ./files/$userid/ not just the main folder. For example: /files/$userid/folder1/folder2/

我当前的代码是:

HTML:

<select name="myDirs">
<option value=""  selected="selected">Select a folder</option>

PHP:

if (chdir("./files/" . $userid)) {

       $dirs = glob('*', GLOB_ONLYDIR);
       foreach($dirs as $val){
          echo '<option value="'.$val.'">'.$val."</option>
";
       }        
        } else {
       echo 'Changing directory failed.';
}

推荐答案

RecursiveDirectoryIterator 应该可以解决问题.不幸的是,文档不是很好,所以这里是一个例子:

RecursiveDirectoryIterator should do the trick. Unfortunately, the documentation is not great, so here is an example:

$root = '/etc';

$iter = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST,
    RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);

$paths = array($root);
foreach ($iter as $path => $dir) {
    if ($dir->isDir()) {
        $paths[] = $path;
    }
}

print_r($paths);

这会在我的计算机上生成以下输出:

This generates the following output on my computer:

Array
(
    [0] => /etc
    [1] => /etc/rc2.d
    [2] => /etc/luarocks
    ...
    [17] => /etc/php5
    [18] => /etc/php5/apache2
    [19] => /etc/php5/apache2/conf.d
    [20] => /etc/php5/mods-available
    [21] => /etc/php5/conf.d
    [22] => /etc/php5/cli
    [23] => /etc/php5/cli/conf.d
    [24] => /etc/rc4.d
    [25] => /etc/minicom
    [26] => /etc/ufw
    [27] => /etc/ufw/applications.d
    ...
    [391] => /etc/firefox
    [392] => /etc/firefox/pref
    [393] => /etc/cron.d
)

这篇关于PHP - 在下拉菜单中递归列出所有目录和子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆