php - 如何使用 PHP 列出按字母顺序排序的目录中的所有文件?

标签 php sorting directory readdir opendir

我正在使用以下 PHP 代码列出当前目录下的所有文件和文件夹:

<?php
    $dirname = ".";
    $dir = opendir($dirname);

    while(false != ($file = readdir($dir)))
        {
          if(($file != ".") and ($file != "..") and ($file != "index.php"))
             {
              echo("<a href='$file'>$file</a> <br />");
        }
    }
?>

问题是列表没有按字母顺序排序(也许它是按创建日期排序的?我不确定)。

如何确保它按字母顺序排序

最佳答案

manual明确地说:

readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

您可以做的是将文件存储在一个数组中,对其进行排序,然后将其内容打印为:

$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                $files[] = $file; // put in array.
        }   
}

natsort($files); // sort.

// print.
foreach($files as $file) {
        echo("<a href='$file'>$file</a> <br />\n");
}

关于php - 如何使用 PHP 列出按字母顺序排序的目录中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3977500/

相关文章:

php - WHEN 子句中具有多个条件的 MySQL CASE

php - 在 PHP 中将数组值乘以/除以 $var 的最体面的方法

c++ - C++ 中的合并排序实现问题

java - 实现自定义比较器

c++ - 从数组中删除并移动

python-2.7 - python setup.py 在安装时创建空目录

php - 如何获取数据库中列的多个数据值?

python - 从python的目录树中收集匹配条件的所有目录

Python - 任何将相对路径转换为绝对路径的方法?

php - Paypal 自适应链式支付 - 发件人的金额是主要收款人的金额而不是总金额。怎么修?