我使用以下
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"); }