This abstract iterator filters out unwanted values. This class should be extended to implement custom iterator filters. The FilterIterator::accept()
must be implemented in the subclass.
class OnlyActiveFilter extends FilterIterator { public function accept() { } }
In accept()
method we will apply logic on whatever $this->current() method will return as shown below. In the below method we are testing against current element is active or not , depending on the response we are returning a Boolean true or false. If the result is false that element will be removed form the result and vice versa.
class OnlyActiveFilter extends FilterIterator { public function accept() { $item = $this->current(); if ($item['is_active'] == 1) { return true; } return false; } }
How to use
$data = [['id' => 1,'name' => 'arjun','email' => '[email protected]','is_active' => 1], ['id' => 2,'name' => 'pravinh','email' => '[email protected]','is_active' => 0]]; $result = new OnlyActiveFilter(new ArrayIterator($data)); foreach ($result as $key => $value) { print_r($value); } // Array ( [id] => 1 [name] => arjun [email] => [email protected] [is_active] => 1 )