迭代器的概念:
![PHP編程--迭代器(乾貨,愛拿不拿)](http://p2.ttnews.xyz/loading.gif)
通過Iterator接口定義的迭代器
(一)ArrayIterator迭代器
多用於遍歷數組。
/**------------------------------------------------------------
* file name: ArrayIterator.php
* ------------------------------------------------------------
* input:
* ------------------------------------------------------------
* output:
* ------------------------------------------------------------
* description:
* PHP迭代器講義
*
* ArrayIterator迭代器多用於對數組的迭代,他能完成一般遍歷方法無法完場的
* 操作!
* ------------------------------------------------------------*/
echo '
';#構建數組
$array = [
'first' => 'first value',
'second' => 'second value',
'third' => 'third value',
'fourth' => 'fourth value',
'fifth' => 'fifth value',
];
/*
* foreach ($array as $key => $value){
* echo '鍵名:' . $key . '|' . '鍵值' . $value . '
';* }
*
* 結果:
* 鍵名: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 . '
';}
結果:
鍵名: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() . '
';$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() . '
';$iterator -> next();
}
閱讀更多 冰雪緣 的文章
關鍵字: PHP