(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveFilterIterator::__construct — 从RecursiveIterator创建一个RecursiveFilterIterator
示例 #1 基本的RecursiveFilterIterator() 示例
<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
public function accept() {
// 如果可以递归到当前项或其值为以"test"开头的值,则接受当前项
return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
}
}
$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new TestsOnlyFilter($iterator);
foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>
以上示例将输出类似以下内容
test1 test3 test4 test5
示例 #2 RecursiveFilterIterator() 示例
<?php
class StartsWithFilter extends RecursiveFilterIterator {
protected $word;
public function __construct(RecursiveIterator $rit, $word) {
$this->word = $word;
parent::__construct($rit);
}
public function accept() {
return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
}
public function getChildren() {
return new self($this->getInnerIterator()->getChildren(), $this->word);
}
}
$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new StartsWithFilter($iterator, "test");
foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>
以上示例将输出类似以下内容
test1 test3 test4 test5