4

scandir的PHP 手册:默认情况下,排序顺序是按字母升序排列的

我正在构建一个文件浏览器(在 Windows 中),所以我希望返回的地址按文件夹/文件排序,然后在这些子集中按字母顺序排列。

示例:现在,我扫描并输出

Aardvark.txt
BarDir
BazDir
Dante.pdf
FooDir

而且我要

BarDir
BazDir
FooDir
Aardvark.txt
Dante.pdf

除了一个usortis_dir()解决方案(我可以自己弄清楚)之外,是否有一种快速有效的方法来做到这一点?

此评论的忍者走在正确的轨道上 - 这是最好的方法吗?

4

3 回答 3

5

这会给你想要的吗?

function readDir($path) {

    // Make sure we have a trailing slash and asterix
    $path = rtrim($path, '/') . '/*';

    $dirs = glob($path, GLOB_ONLYDIR);

    $files = glob($path);

    return array_unique(array_merge($dirs, $files));

}

$path = '/path/to/dir/';

readDir($path);

请注意,您不能glob('*.*')获取文件,因为它会选择名为like.this.

于 2010-12-02T05:12:25.667 回答
3

请试试这个。一个按文件和文件夹(目录)对 PHP scandir结果进行排序的简单函数:

function sort_dir_files($dir)
{
        $sortedData = array();
        foreach(scandir($dir) as $file)
        {
                if(is_file($dir.'/'.$file))
                        array_push($sortedData, $file);
                else
                        array_unshift($sortedData, $file);
        }
        return $sortedData;
}
于 2012-09-08T22:04:48.310 回答
0

我参加聚会迟到了,但我喜欢用readdir()而不是用glob(). 我从解决方案中缺少的是您的解决方案的递归版本。但是使用 readdir 它比使用 glob 更快。

所以使用 glob 它看起来像这样:

function myglobdir($path, $level = 0) {
    $dirs   = glob($path.'/*', GLOB_ONLYDIR);
    $files  = glob($path.'/*');
    $all2   = array_unique(array_merge($dirs, $files));
    $filter = array($path.'/Thumbs.db');
    $all    = array_diff($all2,$filter);

    foreach ($all as $target){
        echo "$target<br />";
        if(is_dir("$target")){
            myglobdir($target, ($level+1));
        }
    }
}

这一个与 readdir 但具有基本相同的输出:

function myreaddir($target, $level = 0){
    $ignore = array("cgi-bin", ".", "..", "Thumbs.db");
    $dirs = array();
    $files = array();

    if(is_dir($target)){
        if($dir = opendir($target)){
            while (($file = readdir($dir)) !== false){
                if(!in_array($file, $ignore)){
                    if(is_dir("$target/$file")){
                        array_push($dirs, "$target/$file");
                    }
                    else{
                        array_push($files, "$target/$file");
                    }

                }
            }

            //Sort
            sort($dirs);
            sort($files);
            $all = array_unique(array_merge($dirs, $files));

            foreach ($all as $value){
                echo "$value<br />";
                if(is_dir($value)){
                    myreaddir($value, ($level+1));
                }
            }
        }
        closedir($dir);
    }

}

我希望有人会觉得这很有用。

于 2011-09-15T14:51:04.790 回答