包含目录和子目录的数组 PHP 慢

Array with directories and subdirectories PHP slow

我创建了这个函数:

function expandDirectories2($base_dir) {
      $directories = array();
      $folders = glob($base_dir."*", GLOB_ONLYDIR);
      foreach($folders as $file) {
            if($file == '.' || $file == '..') continue;
            $dir = $file;
            if(is_dir($dir)) {
                $directories []= $dir;
                $directories = array_merge($directories, expandDirectories2($dir));
            }
      }
      return $directories;
}

print_r(expandDirectories2("./"));

此函数读取指定文件夹的所有目录和子目录。问题是加载页面需要太多时间,有时会显示 memory_exhausted 错误。

我只想制作一个包含文件夹的目录和子目录的数组。我不想分层,顺序也不重要。

示例: 这是文件夹结构:

   - PARENT FOLDER:
     - 2014
        - 01
        - 02
        - 03
        - 04
        - 05
        - 06
        - 07
        - 08
        - 09
        - 10
        - 11
        - 12
     - 2015
        - 01
        - 02
        - 03
        - 04
        - 05
        - 06
        - 07
        - 08
        - 09
        - 10
        - 11
        - 12

那么数组应该是:

./2014
./2014/01
./2014/02
./2014/03
./2014/04
./2014/05
./2014/06
./2014/07
./2014/08
./2014/09
./2014/10
./2014/11
./2014/12
./2015
./2015/01
./2015/02
./2015/03
./2015/04
./2015/05
./2015/06
./2015/07
./2015/08
./2015/09
./2015/10
./2015/11
./2015/12

顺序并不重要。该数组将不包含文件。仅目录。

我怎样才能更快地做到这一点?

谢谢大家!!!

尝试使用 DirectoryIterator。应该会快很多。

function expandDirectories2($path) {
    $directories = array();
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isDir() && !$fileinfo->isDot()) {
            $directories[]= $fileinfo->getPathname();
            $directories = array_merge($directories, expandDirectories2($fileinfo->getPathname()));
        }
    }
    return $directories;
}

在此处查看更多信息:http://php.net/manual/en/class.directoryiterator.php