如何使用PHP按字母顺序列出目录中的所有文件? [英] How can I list all files in a directory sorted alphabetically using PHP?

查看:109
本文介绍了如何使用PHP按字母顺序列出目录中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the following PHP code to list all files and folders under the current directory:

<?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 />");
        }
    }
?>

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

The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).

如何确保按字母顺序排序

推荐答案

手册明确指出:


readdir

返回目录中下一个文件的文件名。文件名以 的顺序返回,该顺序由文件系统存储

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.

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

What you can do is store the files in an array, sort it and then print it's contents as:

$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按字母顺序列出目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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