This Iterator is very useful for iteration
with filtering,
FilterIterator exposes two extra methods over a regular Iterator. One is accept()
which is called every time in internal iteration and is your key point to perform the
filter. The second one is getInnerIterator(), which returns the current Iterator
inside this FilterIterator.
In this example we use FilterIterator to filter out data while traversing through
a collection.
class GenderFilter extends FilterIterator
{
private $GenderFilter;
public function __construct( Iterator $it, $gender="F" )
{
parent::__construct( $it );
$this->GenderFilter = $gender;
}
//your key point to implement filter
public function accept()
{
$person = $this->getInnerIterator()->current();
if( $person['sex'] == $this->GenderFilter )
{
return TRUE;
}
return FALSE;
}
}
$arr = array(
Chapter 6
[ 157 ]
array("name"=>"John Abraham", "sex"=>"M", "age"=>27),
array("name"=>"Lily Bernard", "sex"=>"F", "age"=>37),
array("name"=>"Ayesha Siddika", "sex"=>"F", "age"=>26),
array("name"=>"Afif", "sex"=>"M", "age"=>2)
);
$persons = new ArrayObject( $arr );
$iterator = new GenderFilter( $persons->getIterator() );
foreach( $iterator as $person )
{
echo $person['name'] .
Pages:
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172