PHP编程-- iterator迭代器
迭代器的概念:
通过Iterator接口定义的迭代器
(一)ArrayIterator迭代器
多用于遍历数组。
纯代码,复制到编辑器预览
<?php
/**------------------------------------------------------------
* file name: ArrayIterator.php
* ------------------------------------------------------------
* input:
* ------------------------------------------------------------
* output:
* ------------------------------------------------------------
* description:
* PHP迭代器讲义
*
* ArrayIterator迭代器多用于对数组的迭代,他能完成一般遍历方法无法完场的
* 操作!
* ------------------------------------------------------------*/
echo '<pre>';
#构建数组
$array = [
'first' => 'first value',
'second' => 'second value',
'third' => 'third value',
'fourth' => 'fourth value',
'fifth' => 'fifth value',
];
/*
* foreach ($array as $key => $value){
* echo '键名:' . $key . '|' . '键值' . $value . '<br />';
* }
*
* 结果:
* 键名:first|键值first value
* 键名:second|键值second value
* 键名:third|键值third value
* 键名:fourth|键值fourth value
* 键名:fifth|键值fifth value
*
* 通过for循环呢?
* for ($i = 0; i < count($array); i++{
* 遍历代码
* }
* */
#实例化 ArrayIterator,把接力棒交给$arrayObj
$arrayObj = new ArrayObject($array);
/*
* print_r($arrayObj);
*
ArrayIterator Object
(
[storage:ArrayIterator:private] => Array
(
[first] => first value
[second] => second value
[third] => third value
[fourth] => fourth value
[fifth] => fifth value
)
)
* */
#获取迭代器
$iterator = $arrayObj -> getIterator();
/*
* print_r($iterator);
*
ArrayIterator Object
(
[storage:ArrayIterator:private] => ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[first] => first value
[second] => second value
[third] => third value
[fourth] => fourth value
[fifth] => fifth value
)
)
)
* */
/*
* foreach ($iterator as $key => $value){
echo '键名:' . $key . '|' . '键值' . $value . '<br />';
}
结果:
键名:first|键值first value
键名:second|键值second value
键名:third|键值third value
键名:fourth|键值fourth value
键名:fifth|键值fifth value
这时候,不能用for循环了。
试试while循环
*/
/*
* 指向第一个节点,也是说双向数据链表的bottom位置
$iterator->rewind();
while ($iterator -> valid()){
echo $iterator -> key() . '|' . $iterator -> current() . '<br />';
$iterator -> next();
}
运行结果:
first|first value
second|second value
third|third value
fourth|fourth value
fifth|fifth value
*/
$iterator->rewind();
#跳过first键名,从second键名开始,用seek方法。
$iterator->seek(1);
while ($iterator -> valid()){
echo $iterator -> key() . '|' . $iterator -> current() . '<br />';
$iterator -> next();
}