我使用下面的代码显示下拉菜单中目录中的所有文件.有谁知道如何按字母顺序排列?我认为它与sort函数有关,我无法弄清楚如何!
<?php
$dirname = "images/";
$images = scandir($dirname);
$dh = opendir($dirname);
while ($file = readdir($dh)) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
closedir($dh);
?>
Run Code Online (Sandbox Code Playgroud)
为什么要使用scandir()读取所有文件名,然后使用readdir()方法循环它们?你可以这样做:
<?php
$dirname = "images/";
$images = scandir($dirname);
// This is how you sort an array, see http://php.net/sort
sort($images);
// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
}
?>
Run Code Online (Sandbox Code Playgroud)
您也可以使用natsort(),它的工作方式与sort()相同,但在"自然顺序"中排序.(而不是排序,1,10,2,20因为它将排序为1,2,10,20.)