1 使用array_filter 数组函数
比如我们将数组里,name为abdul的用户删除
$array = array( array( 'name' => 'Jonathan', 'id' => '5' ), array( 'name' => 'Abdul', 'id' => '22' ) ); function fn_filter($var) { if(strcasecmp($var['name'], 'abdul') == 0){ return false; } return true; } print_r(array_filter($array, "fn_filter"));
2 使用迭代器过滤 FilterIterator
实现与刚才相同的功能
$array = array( array( 'name' => 'Jonathan', 'id' => '5' ), array( 'name' => 'Abdul', 'id' => '22' ) ); class UserFilter extends FilterIterator { private $userFilter;//要过滤掉的文字 //$iterator 迭代器 //$filter 过滤 public function __construct(Iterator $iterator, $filter) { parent::__construct($iterator); $this->userFilter = $filter; } public function accept() { $user = $this->getInnerIterator()->current(); if (strcasecmp($user['name'], $this->userFilter) == 0) { return false; } return true; } } $object = new ArrayObject($array); //去除掉名为abdul的人员 $iterator = new UserFilter($object->getIterator(), 'abdul'); foreach ($iterator as $result) { echo $result['name']; }
3 FilterIterator 类
- FilterIterator::accept — Check whether the current element of the iterator is acceptable 检查迭代器当前元素是否可接受
- FilterIterator::__construct — Construct a filterIterator 构造方法
- FilterIterator::current — Get the current element value 获取当前指针的值
- FilterIterator::key — Get the current key 获取当前指针的key
- FilterIterator::next — Move the iterator forward 将迭代器向前移动
- FilterIterator::rewind — Rewind the iterator 重启迭代器
- FilterIterator::valid — Check whether the current element is valid 检查当前元素是否有效