我正在使用以下 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/