How can I list all files in a directory sorted alphabetically using PHP?

帅比萌擦擦* 提交于 2020-04-05 15:52:27

问题


I'm using the following PHP code to list all files and folders under the current directory:

<?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 />");
        }
    }
?>

The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).

How can I make sure it's sorted alphabetically?


回答1:


The manual clearly says that:

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.

What you can do is store the files in an array, sort it and then print it's contents as:

$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");
}



回答2:


<?php
function getFiles(){
    $files=array();
    if($dir=opendir('.')){
        while($file=readdir($dir)){
            if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
                $files[]=$file;
            }   
        }
        closedir($dir);
    }
    natsort($files); //sort
    return $files;
}
?>

<html>
<head>
</head>
<body>

<h1> List of files </h1>

<ul class="dir">
    <? foreach(getFiles() as $file)
        echo "<li name='$file'><a href='$file'>$file</a></li>";
    ?>
</ul>

</body>
</html>



回答3:


You could put all the directory names inside an array like:

$array[] = $file; 

After that you can sort the array with:

sort($array); 

And then print the links with that content.

I hope this help.




回答4:


<?php
$dirname = ".";
$dir = opendir($dirname);

while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
  $list[] = $file;
}
}

sort($list);

foreach($list as $item) {
echo("<a href='$item'>$item</a> <br />");
}
?>



回答5:


Using glob and sort it should work.




回答6:


I'd recommend moving away from the old opendir()/readdir(). Either use glob() or if you encounter a lot of files in a directory then use the DirectoryIterator Class(es):

http://www.php.net/manual/en/class.directoryiterator.php http://www.php.net/manual/en/function.glob.php

Regards




回答7:


You can use this beautiful script:

http://halgatewood.com/free-php-list-files-in-a-directory-script/



来源:https://stackoverflow.com/questions/3977500/how-can-i-list-all-files-in-a-directory-sorted-alphabetically-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!