PHP目录、子目录和文件列出默认排序顺序


PHP Directory, subdirectory and file Listing default sort order

我想使用php列出所有目录、子目录和文件。

我已经试过以下代码。它返回所有目录、子目录和文件,但没有按正确的顺序显示。

例如:默认顺序为1dir、2dir、7dir、8dir,而在浏览器中显示的是1dir、8dir、7dir、2dir,这是不正确的。

代码:

       function createDir($path = '.')
       {
     if ($handle = opendir($path))
             {
               echo "<ul>";
      while (false !== ($file = readdir($handle)))
      {

   if (is_dir($path.$file) && $file != '.' && $file !='..') {
            printSubDir($file, $path);
         }
               else if ($file != '.' && $file !='..'){
         $allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
    $ext = pathinfo($file, PATHINFO_EXTENSION);
   if(in_array($ext,$allowed) ) {
   $queue[] = $file;
 }
  }
   }
   printQueue($queue, $path);
  echo "</ul>";
    }
   }
       function printQueue($queue, $path)
            {
          sort($queue);
           foreach ($queue as $file)
        {
                  //printFile($file, $path);
       }
       }
        function printFile($file, $path) {
 echo "<li><a href='"".$path.$file."'" target='_blank'>$file</a></li>";
             }
            function printSubDir($dir, $path)
        {
         echo "<li><span class='"toggle'">$dir</span>";
        createDir($path.$dir."/");
     echo "</li>";
   }
         createDir($path);
    ?>

需要帮助修复代码并按正确顺序显示目录、子目录和文件。

我在列出目录文件时遇到了同样的问题。但我使用了DirectoryLister这个代码非常有用。你可以很容易地列出你的文件。

您可以通过以下步骤来实现它。

  1. 下载并提取目录列表器
  2. 将resources/default.config.php复制到resources/config.php
  3. 上传index.php和resources文件夹到您想要列出的文件夹
  4. 将其他文件上载到与index.php相同的目录

我希望这能帮助你

您可以通过循环数组并打印每个目录开始:

public function dirtree($dir, $regex='', $ignoreEmpty=false) {
    if (!$dir instanceof DirectoryIterator) {
        $dir = new DirectoryIterator((string)$dir);
    }
    $dirs  = array();
    $files = array();
    foreach ($dir as $node) {
        if ($node->isDir() && !$node->isDot()) {
            // print_r($node);
            $tree = dirtree($node->getPathname(), $ignoreEmpty);
                // print"<pre>";print_r($tree);
            if (!$ignoreEmpty || count($tree)) {
                $dirs[$node->getFilename()] = $tree;
            }
        } elseif ($node->isFile()) {
            $name = $node->getFilename();
            //if ('' == $regex || preg_match($regex, $name)) {
                $files[] = $name;
        }
    }
    asort($dirs);
    sort($files);
    return array_merge($files, $dirs);
}

像这样使用:

$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);