php spl之迭代器iterator

1.ArrayIterator迭代器

常用方法:

ksort:根据键进行排序
asort:根据值进行排序
seek:将interator里的第一个元素从0开始标记,依次递增,seek是指跳到指定标记
循环时的方法包括current,rewind,key,next,valid.

使用方式:

常用的有foreach和while,其中我们以前所使用的foreach默认使用的就是迭代器方式。

<?php

    $arr= array('1' => 'one',
        '2' => 'two',
        '3' => 'three');

    $arrayobject = new ArrayObject($arr);
    $iterator = $arrayobject->getIterator();

    foreach ($arr as $k => $v) {
        echo $k.'->'.$v;
    }
 //1->one 2->two 3->three

    while($iterator->valid()){
        echo $iterator->key().'->'.$iterator->current();
        $iterator->next();
    }
//1->one 2->two 3->three

    if($iterator->valid()){
        $iterator->seek(2);            
        echo $iterator->current();    // two
    }

2.AppendIterator迭代器

AppendIterator能够按照添加迭代器的顺序顺序一次遍历多个迭代器。

<?php
 $array_a = new ArrayIterator(array('a','b','c'));
    $array_b = new ArrayIterator(array('d','e','f'));
    $it = new AppendIterator();
    $it->append($array_b);
    $it->append($array_a);
    foreach ($it as $key => $value) {
        echo $value."\n";
    }
        //d e f a b c

3.MultipleIterator迭代器

<?php
$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
)

4.FilesystemIterator迭代器

<?php
$it = new FilesystemIterator('E:\yy');
foreach ($it as $finfo) {
    printf("%s\t%s\t%s\t%s\t%8s\t%s\n",
        date("Y-m-d H:i:s",$finfo->getMTime()),
    $finfo->getType(),
    $finfo->getExtension(),
        $finfo->isDir()?"<DIR>":"",
        $finfo->getSize(),
        $finfo->getFileName()
    );
}

输出为:


2014-08-25 15:54:42 dir 1   <DIR>      32768    6.26.0.1
2014-08-25 15:58:06 dir 0   <DIR>      36864    6.31.0.0
2014-08-25 15:58:22 file    xml          209    Launcher.xml
2013-05-21 10:13:14 dir CRT <DIR>       4096    Microsoft.VC90.CRT
2014-08-22 12:59:50 file    exe       623296    Uninstall.exe
2014-08-22 12:46:18 file    exe       133824    YY.exe
2014-08-22 12:50:10 file    exe       806080    yylauncher.exe

你可能感兴趣的:(PHP,迭代器,iterator,spl)