我有一些问题,而试图排序我的opendir。该代码是基本的opendir,并设置为显示url目录。我试图将输出按文件夹类型或字母排序,但我没有运气。下面是代码:
<?
$dir = "../";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "<a href=''>".$file."<a><br>";
}
}
}
?>
我如何将我的$file
排序为字母或文件夹类型?
按文件名排序(与您的代码类似,但有排除项,并且不回显,而是将文件放入数组中,稍后进行排序和回显):
<ul>
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != 'index.php') {
$thelist[] = $file;
}
}
closedir($handle);
}
sort($thelist);
foreach($thelist as $file) {
echo '<li><a href="'.$file.'">'.$file.'</a></li>';
}
?>
</ul>
要按文件类型排序,需要稍微复杂一点:
<ul>
<?php
if ($handle = opendir('.')) {
$thelist = array();
while (false !== ($file = readdir($handle))) {
//Don't show ., .., or any php files
if ($file != "." && $file != ".." && substr($file, -3) != 'php') {
if(is_dir($file)) {
//Add directories to their own filetype that will appear at the beginning
$thelist['aaadir'][] = $file;
} else {
//Add each file to an array based on its filetype
$ext = pathinfo($file, PATHINFO_EXTENSION);
$thelist[$ext][] = $file;
}
}
}
closedir($handle);
}
//Sort the arrays alphabetically by filetype
ksort($thelist);
foreach($thelist as $filetype) {
//sort this list of files (in a specific filetype) alphabetically
sort($filetype);
foreach($filetype as $file) {
echo '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
?>
</ul>
您可以从下面的脚本开始。我已经加了注释来解释。
对于排序,将while循环更改为不直接输出,而是按类型将dir或file存储在数组中。然后返回那个数组,我们把它命名为dircontent。然后对dircontent应用sort()函数。然后foreach over dircontent输出已排序的文件和文件夹(您之前保存了该类型,因此您再次知道它是文件还是文件夹)。
如果你想在层次结构中更深入,在is_dir()检查中加入一个showDir($dir)。
<?php
/**
* List the folders of a dir and show only PHP files.
*/
function showDir($dir)
{
$handle = opendir($dir);
while ($dir = readdir($handle)) {
// exclude dot files/folders
if ($dir === '.' or $dir === '..') {
continue;
}
// is this a dir?
if(is_dir($dir)) {
echo '<a href=' . $dir . '>' . $dir . '<a><br>';
}
// is it a file?
if(is_file($dir)) {
// get file extension, in order to check if it's a PHP file
$ext = pathinfo($dir, PATHINFO_EXTENSION);
// is it a PHP file?
if($ext === 'php') {
// indent files a bit
echo '|- ' . $dir . '<br>';
}
}
}
closedir($handle);
}
showDir(".");
?>
请记住,还有其他解决方案:例如scandir(), glob()或DirectoryIterator()。opendir()/readdir()/closedir()方法有点生疏,但可以工作。