本文共 2225 字,大约阅读时间需要 7 分钟。
ArrayIterator 是 PHP 中默认与 foreach循环配合使用的迭代器,它提供了一系列高级功能。通过 ArrayIterator 可以实现定位、排序以及其他高级操作。
$arr = array( 'apple' => 'apple value', 'orange' => 'orange value', 'grape' => 'grape value', 'plum' => 'plum value');$obj = new ArrayObject($arr);$it = $obj->getIterator();foreach ($it as $key => $value) { echo $key . ":" . $value . "\n";}$it->rewind();while ($it->valid()) { echo $it->key() . " : " . $it->current() . "\n"; $it->next();}$it->seek(1);while ($it->valid()) { echo $it->key() . " : " . $it->current() . "\n"; $it->next();}$it->ksort(); // 对键进行字典序排序foreach ($it as $key => $value) { echo $key . ":" . $value . "\n";} apple:apple valueorange:orange valuegrape:grape valueplum:plum valueapple : apple valueorange : orange valuegrape : grape valueplum : plum valueorange : orange valuegrape : grape valueplum : plum valueapple:apple valuegrape:grape valueorange:orange valueplum:plum value
AppendIterator 可以将多个迭代器连接起来,实现多次遍历的功能。以下是 AppendIterator 的使用示例:
$arr_a = new ArrayIterator(array( 'a' => array('a', 'b' => 234), 'b' => 'b', 'c' => 'c'));$arr_b = new ArrayIterator(array('d', 'e', 'f'));$it = new AppendIterator();$it->append($arr_a);$it->append($arr_b);foreach ($it as $key => $value) { print_r($key); echo "-{$value}---------------";} a-Array ( [0] => a [b] => 234 ) ---------------0-b---------------1-c---------------0-d---------------1-e---------------2-f---------------
MultipleIterator 用于将多个迭代器的数据组合起来,形成一个整体来访问。以下是 MultipleIterator 的使用示例:
$idIter = new ArrayIterator(array('01', '02', '03'));$nameIter = new ArrayIterator(array('张三', '李四', '王五'));$ageIter = new ArrayIterator(array('22', '23', '25'));$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);$mit->attachIterator($idIter, "ID");$mit->attachIterator($nameIter, "NAME");$mit->attachIterator($ageIter, "AGE");foreach ($mit as $value) { print_r($value);} Array( [ID] => 01 [NAME] => 张三 [AGE] => 22)Array( [ID] => 02 [NAME] => 李四 [AGE] => 23)Array( [ID] => 03 [NAME] => 王五 [AGE] => 25)
以上是对 PHP 迭代器的详细介绍,涵盖了 ArrayIterator、AppendIterator 和 MultipleIterator 的核心功能及其使用示例。
转载地址:http://hrvfk.baihongyu.com/