Exclude folders from recursion in recursive directory iterator php

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-05 07:15:18

问题


I need to exclude all files and folders from a certain directories while doing the recursion. I have this code so far :

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($websiteRoot.$file["filepathfromroot"]));
     foreach ($it as $currentfile)
     {
      if (!$it->isDot()&&$it->isFile()&&!in_array($it->getSubPath(), $file["exclude-directories"])) {

        //do something
         }
     }

However this subpath will only match for children and and not files and sub directories off the children. i.e For a directory structure of Foo/bar/hello.php. If you add Foo to the exclude list hello.php would still come in the result.

Does anyone have a solution for this ?


回答1:


Replace :

in_array($it->getSubPath(), $file["exclude-directories"])

By something like :

!in_array_beginning_with($it->getSubPath(), $file["exclude-directories"])

And you implement the function :

function in_array_beginning_with($path, $array) {
  foreach ($array as $begin) {
    if (strncmp($path, $begin, strlen($begin)) == 0) {
      return true;
    }
  }
  return false;
}

But that's not a very good way because you will recursivly get into useless directories even if they are very big and deep. In your case, I'll suggest you to do a old-school recursive function to read your directory :

<?php

function directory_reader($dir, array $ignore = array (), array $deeps = array ())
{
    array_push($deeps, $dir);
    $fulldir = implode("/", $deeps) . "/";
    if (is_dir($fulldir))
    {
        if (($dh = opendir($fulldir)) !== false)
        {
            while (($file = readdir($dh)) !== false)
            {
                $fullpath = $fulldir . $file;
                if (in_array($fullpath, $ignore)) {
                    continue ;
                }

                // do something with fullpath
                echo $fullpath . "<br/>";

                if (is_dir($fullpath) && (strcmp($file, '.') != 0) && (strcmp($file, '..') != 0))
                {
                    directory_reader($file, $ignore, $deeps);
                }
            }
            closedir($dh);
        }
    }
    array_pop($deeps);
}

If you try directory_reader(".", array("aDirectoryToIngore")), it will not be read at all.



来源:https://stackoverflow.com/questions/12454114/exclude-folders-from-recursion-in-recursive-directory-iterator-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!