如何使用PHP按字母顺序对文件夹目录进行排序


how to sort out folder directory by alphabetically using php

如何使用php按字母顺序对文件夹目录进行排序 请帮助我解决这个问题,这不是[重复]帖子谢谢。

此代码如下所示(按时间排序)

  • 苹果
  • 娃娃
  • 飞机
  • 香蕉

我想要这样

美国广播公司

  • 飞机
  • 苹果
  • 苹果
  • 香蕉

DEF

  • 娃娃

PHP代码

<?php
    function folderlist(){
      $startdir = './';
      $ignoredDirectory[] = '.'; 
      $ignoredDirectory[] = '..';
       if (is_dir($startdir)){
           if ($dh = opendir($startdir)){
               while (($folder = readdir($dh)) !== false){
                   if (!(array_search($folder,$ignoredDirectory) > -1)){
                     if (filetype($startdir . $folder) == "dir"){
                           $directorylist[$startdir . $folder]['name'] = $folder;
                           $directorylist[$startdir . $folder]['path'] = $startdir;
                       }
                   }
               }
               closedir($dh);
           }
       }
    return($directorylist);
    }

    $folders = folderlist();
    sort($folders);
        foreach ($folders as $folder){
        $path = $folder['path'];
        $name = $folder['name'];


    echo '<div class="menu">
    <h3 class="headerbar"><a href="' .$path .'index2.php?folder=' .$name . '" class="style1"><span class="headertit">' .$name . '</span></a></div>';
      }
    ?>

你对sort的调用替换为如下内容:

usort($folders, function ($a, $b) {
    return strnatcmp($a['name'], $b['name']);
}); 

此外,您可能希望通过使用目录迭代器或 scandir 来降低代码复杂性

你应该尝试使用 scandir()。 默认情况下,scandir() 将按字母顺序对文件进行排序:

$dir    = './';
$files1 = scandir($dir);
print_r($files1);

http://php.net/manual/en/function.scandir.php