0
我有一個列出目錄內所有文件的頁面,如果可能的話,我希望它們按字母順序排序。不太確定如何做到這一點。以下是當前的代碼。如果任何人有任何想法,真棒!PHP - 按字母順序列出目錄文件
usort($retval, function($dirA, $dirB) {
return strnatcmp($dirA['name'], $dirB['name']);
});
請注意,你需要有PHP 5.3:
<?php
function getFileList($dir)
{
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// open pointer to directory and read list of files
$d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
if(is_dir("$dir$entry")) {
$retval[] = array(
"name" => "$dir$entry/",
"type" => filetype("$dir$entry"),
"size" => 0,
"lastmod" => filemtime("$dir$entry")
);
} elseif(is_readable("$dir$entry")) {
$retval[] = array(
"name" => "$dir$entry",
"type" => mime_content_type("$dir$entry"),
"size" => filesize("$dir$entry"),
"lastmod" => filemtime("$dir$entry")
);
}
}
$d->close();
return $retval;
}
?>
<?php
// list files in the current directory
$dirlist = getFileList(".");
$dirlist = getFileList("./");
?>
<?php
echo "<div id=\"menu\">";
echo "<div class=\"menu1 title\">Name</div><div class=\"menu2 title\">Last Modified</div>\n";
foreach($dirlist as $file) {
echo "<div class=\"menu1\"><a href=\"{$file['name']}\" target=\"_blank\">",number_format(++$counter),". ",basename($file['name']),"</div>\n";
echo "<div class=\"menu2\">",date('r', $file['lastmod']),"</div>\n";
}
echo "<div class=\"clear\"></div>\n";
echo "</div>\n";
?>
這讓我走向了正確的方向。 「natsort」並沒有完全做到,而是「排序」。謝謝! – user1610904