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

时间:2015-02-25 06:49:25

标签: php file function directory subdirectory

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

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

对于ex:默认顺序是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);
    ?>

需要帮助来修复代码并以正确的顺序显示direcotry,子目录和文件。

2 个答案:

答案 0 :(得分:0)

我在列出目录文件时遇到了同样的问题。但是我使用了DirectoryLister 这段代码非常有用。您可以轻松列出您的文件。

您可以按照以下步骤实施。

  1. 下载并解压缩目录列表
  2. 将resources / default.config.php复制到resources / config.php
  3. 将index.php和resources文件夹上传到要列出的文件夹
  4. 将其他文件上传到index.php
  5. 所在的目录

    我希望这可以帮到你

答案 1 :(得分:0)

您可以先循环数组并打印每个目录:

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);
相关问题