有个非常好的案例就是遍历目录。通例的做法就是使用 scandir ,然后跳过「.「 和 「..」,以及其它未知足条件的文件。例如你需要遍历个某个目录抽取其中的图片文件,就需要判断是否是 jpg、gif 末端。
下面的代码就是使用 SPL 的迭代器执行上述递归寻找指定目录中的图片文件的例子
class RecursiveFileFilterIterator extends FilterIterator {
// 知足条件的扩展名
protected $ext = array('jpg','gif');
/**
* 提供 $path 并天生对应的目录迭代器
*/
public function __construct($path) {
parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}
/**
* 检查文件扩展名是否知足条件
*/
public function accept() {
$item = $this->getInnerIterator();
if ($item->isFile() &&
in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext)) {
return TRUE;
}
}
}
// 实例化
foreach (new RecursiveFileFilterIterator('/path/to/something') as $item) {
echo $item . PHP_EOL;
}
?>
原文链接:https://www.cnblogs.com/lz0925/p/12876438.html
本站声明:网站内容来源于网络,若有侵权,请联系我们,我们将及时处理。