如何使用 PHP 列出按字母顺序排序的目录中的所有文件?
我使用以下 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 />");
}
}
?>
问题是列表不是按字母顺序排序的(也许它是按创建日期排序的?我不确定)。
我如何确保它按字母顺序排序?
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).
How can I make sure it's sorted alphabetically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我建议放弃旧的 opendir()/readdir()。使用 glob() 或者如果您在目录中遇到很多文件,则使用 DirectoryIterator 类:
http://www.php.net/manual/en/class.directoryiterator.php
http://www.php.net/manual/en/function.glob.php
问候
I'd recommend moving away from the old opendir()/readdir(). Either use glob() or if you encounter a lot of files in a directory then use the DirectoryIterator Class(es):
http://www.php.net/manual/en/class.directoryiterator.php
http://www.php.net/manual/en/function.glob.php
Regards
您可以使用这个漂亮的脚本:
http://halgatewood.com /free-php-list-files-in-a-directory-script/
You can use this beautiful script:
http://halgatewood.com/free-php-list-files-in-a-directory-script/
手册明确指出:
您可以做的是将文件存储在数组中,对其进行排序,然后将其内容打印为:
The manual clearly says that:
What you can do is store the files in an array, sort it and then print it's contents as:
使用 glob 和 排序它应该可以工作。
Using glob and sort it should work.
您可以将所有目录名称放入一个数组中,例如:
之后您可以使用以下方法对数组进行排序:
然后打印包含该内容的链接。
我希望这有帮助。
You could put all the directory names inside an array like:
After that you can sort the array with:
And then print the links with that content.
I hope this help.