迭代器:通过某种统一的方式遍历链表或者数组中的元素的过程叫做迭代遍历,而这种统一的遍历工具称为迭代器。
//SPL迭代器之ArrayIterator
$fruits = array(
"apple" => "apple value",
"orange" => "orange value",
"grape" => "grape value",
"plum" => "plum value"
);
print_r($fruits);
echo "**** use fruits directly *****" . "\n";
foreach ($fruits as $key => $value) {
echo $key . ":" . $value . "\n";
}
//使用ArrayIterator遍历数组
$obj = new ArrayObject($fruits);
$it = $obj->getIterator();
echo "**** use ArrayIterator in foreach *****" . "\n";
foreach ($it as $key => $value) {
echo $key . ":" . $value . "\n";
}
echo "**** use ArrayIterator in while *****" . "\n";
$it->rewind();//调用current之前一定要调用rewind
while ($it->valid()) {
echo $it->key() . ":" . $it->current() . "\n";
$it->next();//这句一定不能少
}
//跳过某些元素进行打印
echo "**** use week before while *****" . "\n";
$it->rewind();
if($it->valid()) {
$it->seek(1);
while ($it->valid()) {
echo $it->key() . ":" . $it->current() . "\n";
$it->next();//这句一定不能少
}
}
echo "**** use ksort *****" . "\n";//用key进行字典序排序
$it->ksort();
foreach ($it as $key => $value) {
echo $key . ":" . $value . "\n";
}
echo "**** use asort *****" . "\n";//用value进行字典序排序
$it->asort();
foreach ($it as $key => $value) {
echo $key . ":" . $value . "\n";
}