我想按字母顺序对文件进行排序,但我不知道该怎么做。我的意思是,我希望目录将是ABC订单的第一个目录,以及ABC订购的文件之后。 我尝试了几种选择,但我不能这样做。 这是我的代码:
<?php
$dirlist = getFileList("./members/files/");?>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Size</th>
<th>Last Modified</th>
</tr>
</thead>
<tbody>
<?php
// output file list as table rows
foreach($dirlist as $file) {
echo "<tr>\n";
$file['nams'] = basename($file['name']);
$file['nams2'] = pathinfo($file['nams'], PATHINFO_EXTENSION );
$file['nams'] = pathinfo($file['nams'], PATHINFO_FILENAME);
if($file['nams2'] != 'mp4' && $file['nams2'] != '')
{
echo "<td><a href=\"/members/get_file.php?name={$file['nams']}&ext={$file['nams2']}\">",basename($file['name']),"</a></td>\n";
} else if($file['nams2'] != '') {
echo "<td><a href=\"/video.php?name={$file['nams']}\">",basename($file['name']),"</a></td>\n";
} else {
echo "<td><a href=\"#\">",basename($file['name']),"</a></td>\n";
}
echo "<td>{$file['type']}</td>\n";
echo "<td>{$file['size']}</td>\n";
echo "<td>",date('Y-m-d H:i', $file['lastmod']),"</td>\n";
echo "</tr>\n";
}
?>
</tbody>
</table>
<?php
function getFileList($dir, $recurse=false, $depth=false)
{
$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")
);
if($recurse && is_readable("$dir$entry/")) {
if($depth === false) {
$retval = array_merge($retval, getFileList("$dir$entry/", true));
} elseif($depth > 0) {
$retval = array_merge($retval, getFileList("$dir$entry/", true, $depth-1));
}
}
} elseif(is_readable("$dir$entry")) {
$retval[] = array(
"name" => "$dir$entry",
"type" => mime_content_type("$dir$entry"),
"size" => formatSizeUnits(filesize("$dir$entry")),
"lastmod" => filemtime("$dir$entry")
);
}
}
$d->close();
return $retval;
}
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' kB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
?>
答案 0 :(得分:0)
您可以使用scandir
以数组的形式返回已排序的文件列表。
示例:强>
<?php
$directory_list = scandir("./members/files/");
print_r($directory_list);
这将输出类似于:
的目录列表Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
...
)
你可以这样做,按降序排序:
print_r($directory_list, SCANDIR_SORT_DESCENDING);
您可以在PHP documentation中找到有关scandir
的更多信息。