加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

如何列出使用PHP按字母顺序排列的目录中的所有文件?

发布时间:2020-05-31 01:37:32 所属栏目:PHP 来源:互联网
导读:我使用以下 PHP代码列出当前目录下的所有文件和文件夹: ?php $dirname = .; $dir = opendir($dirname); while(false != ($file = readdir($dir))) { if(($file != .) and ($file != ..) and ($file !

我使用以下 PHP代码列出当前目录下的所有文件和文件夹:

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

问题是列表不按字母顺序排列(也许按创建日期排序?我不确定).

我如何确保按字母顺序排列?

manual清楚地说:

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.

您可以做的是将文件存储在数组中,对其进行排序,然后将其打印为:

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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读