dongpa3109 2015-07-24 09:43
浏览 46
已采纳

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

I created this function:

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("./"));

This function read all directories and subdirectories of a specified folder. The problem is it takes so much to load the page and sometimes it shows memory_exhausted error.

I only want to make an array with directories and subdirectories of a folder. I don't want to be hierarchical and the ordering isn't important.

Example: This is the folder structure:

   - 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

Then the array should be:

./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

The ordering is not important. The array will not contain files. Only dirs.

How can I do this faster?

Thank you all!!!

  • 写回答

1条回答 默认 最新

  • dsgwoh7038 2015-07-24 10:08
    关注

    Try using DirectoryIterator. It should be much faster.

    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;
    }
    

    Check more info here: http://php.net/manual/en/class.directoryiterator.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度