【问题标题】:Exclude folders from recursion in recursive directory iterator php在递归目录迭代器php中从递归中排除文件夹
【发布时间】:2012-09-17 06:30:07
【问题描述】:

在进行递归时,我需要从某个目录中排除所有文件和文件夹。到目前为止我有这个代码:

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

但是,此子路径仅匹配子路径,而不匹配子路径的文件和子目录。即对于 Foo/bar/hello.php 的目录结构。如果将 Foo 添加到排除列表 hello.php 仍然会出现在结果中。

有没有人可以解决这个问题?

【问题讨论】:

  • 这不是因为您使用的是主要对象,而不是它本身的文件表示吗?例如。 $it->isDot() 应该是 $currentFile->isDot()
  • 我更改了它,但当前文件是一个 splfileinfo 对象,它没有 getsubpath 函数或 isdot 函数。

标签: php directory-listing


【解决方案1】:

替换:

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

通过类似:

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

你实现了这个功能:

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

但这不是一个很好的方法,因为即使它们很大很深,您也会递归地进入无用的目录。在您的情况下,我建议您使用老式递归函数来读取您的目录:

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

如果你尝试directory_reader(".", array("aDirectoryToIngore")),它根本不会被读取。

【讨论】:

    猜你喜欢
    • 2022-09-26
    • 2013-12-01
    • 2013-08-18
    • 2012-11-06
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多