我尝试了几种方法来忽略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