5

我尝试了几种方法来忽略RecursiveIteratorIterator文件系统上使用的某些目录。

举例来说,我想忽略以下目录:/cache.

我的Iterator样子是这样的:

//$dirname is root
$directory = new RecursiveDirectoryIterator($dirname);
$mega = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);

foreach ($mega as $fileinfo) {
 echo $fileinfo;
}

例如,我已经能够忽略某些文件扩展名pathinfo

$filetypes = array("jpg", "png");
$filetype = pathinfo($fileinfo, PATHINFO_EXTENSION);

foreach ($mega as $fileinfo) {
    if (!in_array(strtolower($filetype), $filetypes)) {
    echo $fileinfo;
    }
}

当我使用PATHINFO_DIRNAME(使用数组中的适当目录路径)尝试它时,它不起作用,没有错误,它只是不忽略目录。

我也尝试过使用FilterIterator无济于事,现在我在想也许我应该使用RegexIterator.

使用 忽略目录的最简单和最有效的方法是RecursiveIteratorIterator什么?


没用的实验。使用PATHINFO_DIRNAME

$dirignore = array("cache", "cache2");
$directory = new RecursiveDirectoryIterator($dirname);
$mega = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
$dirtype = pathinfo($fileinfo, PATHINFO_DIRNAME); 

if (!in_array($dirtype), $dirignore)) {
echo $fileinfo;  //no worky still echo directories
}

使用FilterIterator(不确定这是如何工作的)

class DirFilter extends FilterIterator
{
    public function accept()
    {
        //return parent::current() != "..\cache\";

       $file = $this->getInnerIterator()->current();
       if ($file != "..\cache")
       return $file->getFilename();

      //also tried with same error as below
      //return !preg_match('/\cache', $file->getFilename());
    }
}

$directory= new RecursiveDirectoryIterator($dirname);
$directory = new DirFilter($directory); 
$mega = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
// loop

这导致Error: An instance of RecursiveIterator or IteratorAggregate creating it is required

4

1 回答 1

9

DirFilter想要扩展RecursiveFilterIterator,因为它与递归迭代器一起使用。不这样做,是你错误的原因。

class DirFilter extends RecursiveFilterIterator
{
    // …
}

下一步是弄清楚如何accept()正确使用。它应该返回一个trueorfalse值,它指示当前项是应该包含 ( true) 还是排除 ( false) 从迭代中。从返回文件名accept()不是您想要做的。

class DirFilter extends RecursiveFilterIterator
{
    public function accept()
    {
        $excludes = array("cache", "cache2");
        return !($this->isDir() && in_array($this->getFilename(), $excludes));
    }
}

能够传入排除目录的数组可能会很好。这需要更多的代码,但更可重用。

class DirFilter extends RecursiveFilterIterator
{
    protected $exclude;
    public function __construct($iterator, array $exclude)
    {
        parent::__construct($iterator);
        $this->exclude = $exclude;
    }
    public function accept()
    {
        return !($this->isDir() && in_array($this->getFilename(), $this->exclude));
    }
    public function getChildren()
    {
        return new DirFilter($this->getInnerIterator()->getChildren(), $this->exclude);
    }
}

然后可以像这样使用此代码:

$directory = new RecursiveDirectoryIterator($dirname);
$filtered = new DirFilter($directory, $dirignore); 
$mega = new RecursiveIteratorIterator($filtered, …);
于 2013-03-12T19:32:51.033 回答