::解::
使用@RomanPerekhrest回答略有修改,我有我需要的东西.这会添加多个目录以递归搜索,同时过滤掉某些文件夹(在我的情况下:“_ _thumbs”文件夹).最终代码如下:
$dir1 = new RecursiveDirectoryIterator("./folder01");
$dir2 = new RecursiveDirectoryIterator("./folder02");
$dir3 = new RecursiveDirectoryIterator("./folder03");
$iterators = new AppendIterator();
$filter = function ($file, $key, $iterator) {
if ($iterator->hasChildren() && $file->getFilename() != "_thumbs") {
return true;
}
return $file->isFile();
};
$iterators->append(new RecursiveIteratorIterator( $dir1 ));
$iterators->append( $dir2 );
$iterators->append(new RecursiveIteratorIterator(new RecursiveCallbackFilterIterator($dir3, $filter)));
$rgIt = new RegexIterator($iterators, "/^.+\.jpg$/i");
$files = iterator_to_array($rgIt);
::原始问题::
我很难搞清楚RegexIterator.我正在尝试过滤掉RecursiveIteratorIterator扫描的父目录中的目录.在我的下面的代码中,$dir3有多个目录,因此RecursiveIteratorIterator,但它也有一个“_thumbs”目录,我不希望它处理. RegexIterator目前正在过滤并保留.jpg图像,但我还要杀死从“_thumbs”目录中获取的任何内容.
$dir1 = new RecursiveDirectoryIterator("./folder01");
$dir2 = new RecursiveDirectoryIterator("./folder02");
$dir3 = new RecursiveDirectoryIterator("./folder03"); // <<< this dir has a _thumbs directory that I don't want to process
$iterators = new AppendIterator();
$iterators->append(new RecursiveIteratorIterator( $dir1 ));
$iterators->append( $dir2 );
$iterators->append(new RecursiveIteratorIterator( $dir3 ));
$rgIt = new RegexIterator($iterators, "/^.+\.jpg$/i"); //<<< this filters and keeps .jpg images. I don't fully understand the syntax though
$files = iterator_to_array($rgIt);
usort($files, function($a, $b){
if(filectime($a) == filectime($b)){
return 0;
}
return filectime($a) > filectime($b) ? -1 : 1;
});
$files = array_slice($files, 0 , 18);
:: EDIT01 ::
这是我试过的另一个测试,但也没有随处可见.尝试使用RecursiveFilterIterator,但我怀疑我是否正确使用它.我得到的错误说“传递给RecursiveFilterIterator :: __ construct()的参数1必须实现接口RecursiveIterator,给出的AppendIterator实例”.
$dir1 = new RecursiveDirectoryIterator("./folder01");
$dir2 = new RecursiveDirectoryIterator("./folder02");
$dir3 = new RecursiveDirectoryIterator("./folder03");
$iterators = new AppendIterator();
$iterators->append(new RecursiveIteratorIterator( $dir1 ));
$iterators->append( $dir2 );
$iterators->append(new RecursiveIteratorIterator( $dir3 ));
class DirFilter extends RecursiveFilterIterator{
public function accept(){
$excludes = "/_thumbs";
return !(in_array($this->getFilename(), $excludes));
}
}
$filterItr = new DirFilter($iterators);
$rgIt = new RegexIterator($filterItr, "/^.+\.jpg$/i");
$files = iterator_to_array($rgIt);
最佳答案 在正则表达式模式中使用否定断言:
...
$rgIt = new RegexIterator($iterators, "/(?!\/_thumbs\/)^.+\.jpg$/i");
$files = iterator_to_array($rgIt);
...
如果上述方法不适合您,请尝试使用RecursiveCallbackFilterIterator过滤掉“拇指”图像:
$filter = function ($file, $key, $iterator) {
if ($iterator->hasChildren() && $file->getFilename() == "_thumbs") {
return true;
}
return $file->isFile();
};
...
$iterators->append( $dir2 );
$iterators->append(new RecursiveIteratorIterator(new RecursiveCallbackFilterIterator($dir3, $filter)));
...