您好,欢迎访问一九零五行业门户网

PHP SPL库 的迭代器类使用详解

spl是standard php library(php标准库)的缩写。
spl提供了多个迭代器类,分别提供了迭代访问、过滤数据、缓存结果、控制分页等功能。,因为php总是在不断壮大,我尽可能列出spl中所有的迭代类。下面其中一些迭代器类是需要php5.4,另外一些如searhiteratoer类在最新的php版本中已经去除
1.arrayiteratoer从php数组创建一个迭代器,当其和iteratoraggregate类一起使用时,免去了直接实现iterator接口的方法的工作。
$b = array( 'name'=> 'mengzhi', 'age' => '12', 'city'=> 'shanghai' ); $a = new arrayiterator($b); $a->append(array( 'home' => 'china', 'work' => 'developer' )); $c = $a->getarraycopy(); print_r($a); print_r($c); /**outputarrayiterator object( [storage:arrayiterator:private] => array ( [name] => mengzhi [age] => 12 [city] => shanghai [0] => array ( [home] => china [work] => developer ) ))array ( [name] => mengzhi [age] => 12 [city] => shanghai [0] => array ( [home] => china [work] => developer ))**/
2. limititerator返回给定数量的结果以及从集合中取出结果的起始索引点:
// create an iterator to be limited $fruits = new arrayiterator(array( 'apple', 'banana', 'cherry', 'damson', 'elderberry' )); // loop over first three fruits only foreach (new limititerator($fruits, 0, 3) as$fruit) { var_dump($fruit); } echo\n; // loop from third fruit until the end // note: offset starts from zero for apple foreach (new limititerator($fruits, 2) as$fruit) { print_r($fruit); } /**outputstring(5) applestring(6) bananastring(6) cherrycherrydamsonelderberry*/
3. appenditerator 按顺序迭代访问几个不同的迭代器。例如,希望在一次循环中迭代访问两个或者更多的组合。这个迭代器的append方法类似于array_merge()函数来合并数组。
$array_a = new arrayiterator(array('a', 'b', 'c')); $array_b = new arrayiterator(array('d', 'e', 'f')); $iterator = new appenditerator; $iterator->append($array_a); $iterator->append($array_b); foreach ($iteratoras$current) { echo$current.\n; } /**outputabcdef*/
4. filteriterator基于outeriterator接口,用于过滤数据,返回符合条件的元素。必须实现一个抽象方法accept(),此方法必须为迭代器的当前项返回true或false
class userfilter extends filteriterator { private$userfilter; publicfunction __construct(iterator $iterator, $filter) { parent::__construct($iterator); $this->userfilter = $filter; } publicfunction accept() { $user = $this->getinneriterator()->current(); if (strcasecmp($user['name'], $this->userfilter) == 0) { return false; } return true; } } $array = array( array( 'name' => 'jonathan', 'id' => '5' ), array( 'name' => 'abdul', 'id' => '22' ) ); $object = new arrayobject($array); //去除掉名为abdul的人员 $iterator = new userfilter($object->getiterator(), 'abdul'); foreach ($iteratoras$result) { echo$result['name']; } /**outputjonathan**/
5. regexiterator继承filteriterator,支持使用正则表达式模式匹配和修改迭代器中的元素。经常用于将字符串匹配。
$a = new arrayiterator(array('test1', 'test2', 'test3')); $i = new regexiterator($a, '/^(test)(\d+)/', regexiterator::replace); $i->replacement = '$2:$1'; print_r(iterator_to_array($i)); /**outputarray( [0] => 1:test [1] => 2:test [2] => 3:test)**/
6. iteratoriterator一种通用类型的迭代器,所有实现了traversable接口的类都可以被它迭代访问。
7. cachingiterator用来执行提前读取一个元素的迭代操作,例如可以用于确定当前元素是否为最后一个元素。
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus'); try { $object = new cachingiterator(new arrayiterator($array)); foreach ($objectas$value) { echo$value; if ($object->hasnext()) { echo','; } } } catch (exception $e) { echo$e->getmessage(); } /**outputkoala,kangaroo,wombat,wallaby,emu,kiwi,kookaburra,platypus**/
8. seekableiterator用于创建非顺序访问的迭代器,允许跳转到迭代器中的任何一点上。
$array = array(apple, banana, cherry, damson, elderberry); $iterator = new arrayiterator($array); $iterator->seek(3); echo$iterator->current(); /**outputdamson**/
9. norewinditerator用于不能多次迭代的集合,适用于在迭代过程中执行一次性操作。
$fruit = array('apple', 'banana', 'cranberry'); $arr = new arrayobject($fruit); $it = new norewinditerator($arr->getiterator()); echofruit a:\n; foreach ($itas$item) { echo$item . \n; } echofruit b:\n; foreach ($itas$item) { echo$item . \n; } /**outputfruit a:applebananacranberryfruit b:**/
10. emptyiterator一种占位符形式的迭代器,不执行任何操作。当要实现某个抽象类的方法并且这个方法需要返回一个迭代器时,可以使用这种迭代器。
11. infiniteiterator用于持续地访问数据,当迭代到最后一个元素时,会再次从第一个元素开始迭代访问。
$arrayit = new arrayiterator(array('cat', 'dog')); $infinite = new infiniteiterator($arrayit); $limit = new limititerator($infinite, 0, 7); foreach ($limitas$value) { echo$value\n; } /**outputcatdogcatdogcatdogcat**/
12. recursivearrayiterator创建一个用于递归形式数组结构的迭代器,类似于多维数组.它为许多更复杂的迭代器提供了所需的操作,如recursivetreeiterator和recursiveiteratoriterator迭代器。
$fruits = array(a => lemon, b => orange, array(a => apple, p => pear)); $iterator = new recursivearrayiterator($fruits); while ($iterator->valid()) { //检查是否含有子节点 if ($iterator->haschildren()) { //输出所以字节点 foreach ($iterator->getchildren() as$key => $value) { echo$key . ' : ' . $value . \n; } } else { echono children.\n; } $iterator->next(); } /**outputno children.no children.a : applep : pear**/
13. recursiveiteratoriterator将一个树形结构的迭代器展开为一维结构。
$fruits = array(a => lemon, b => orange, array(a => apple, p => pear)); $arrayiter = new recursivearrayiterator($fruits); $iteriter = new recursiveiteratoriterator($arrayiter); foreach ($iteriteras$key => $value) { $d = $iteriter->getdepth(); echodepth=$d k=$key v=$value\n; } /**outputdepth=0 k=a v=lemondepth=0 k=b v=orangedepth=1 k=a v=appledepth=1 k=p v=pear**/
14. recursivetreeiterator以可视在方式显示一个树形结构。
$hey = array(a => lemon, b => orange, array(a => apple, p => pear)); $awesome = new recursivetreeiterator( new recursivearrayiterator($hey), null, null, recursiveiteratoriterator::leaves_only ); foreach ($awesomeas$line) echo$line . php_eol; /**output|-lemon|-orange |-apple \-pear**/
15. parentiterator是一个扩展的filteriterator迭代器,它可以过滤掉来自于recursiveiterator迭代器的非父元素,只找出子节点的键值。通俗来说,就是去枝留叶。
$hey = array(a => lemon, b => orange, array(a => apple, p => pear)); $arrayiterator = new recursivearrayiterator($hey); $it = new parentiterator($arrayiterator); print_r(iterator_to_array($it)); /**outputarray ( [0] => array ( [a] => apple [p] => pear ))**/
16. recursivefilteriterator是filteriterator迭代器的递归形式,也要求实现抽象的accept()方法,但在这个方法中应该使用$this->getinneriterator()方法访问当前正在迭代的迭代器。
class testsonlyfilter extends recursivefilteriterator { publicfunction accept() { // 找出含有“叶”的元素 return$this->haschildren() || (mb_strpos($this->current(), 叶) !== false); } } $array = array(叶1, array(李2, 叶3, 叶4), 叶5); $iterator = new recursivearrayiterator($array); $filter = new testsonlyfilter($iterator); $filter = new recursiveiteratoriterator($filter); print_r(iterator_to_array($filter)); /**outputarray( [0] => 叶1 [1] => 叶3 [2] => 叶5)**/
17. recursiveregexiterator是regexiterator迭代器的递归形式,只接受recursiveiterator迭代器作为迭代对象。
$rarrayiterator = new recursivearrayiterator(array('叶1', array('tet3', '叶4', '叶5'))); $rregexiterator = new recursiveregexiterator($rarrayiterator, '/^叶/', recursiveregexiterator::all_matches); foreach ($rregexiteratoras$key1 => $value1) { if ($rregexiterator->haschildren()) { // print all children echochildren: ; foreach ($rregexiterator->getchildren() as$key => $value) { echo$value . ; } echo\n; } else { echono children\n; } } /**outputno childrenchildren: 叶4 叶5**/
18. recursivecachingiterator在recursiveiterator迭代器上执行提前读取一个元素的递归操作。
19. callbackfilteriterator(php5.4)同时执行过滤和回调操作,在找到一个匹配的元素之后会调用回调函数。
$hey = array( 李1, 叶2, 叶3, 叶4, 叶5, 叶6,); $arrayiterator = new recursivearrayiterator($hey); function isye($current) { return mb_strpos($current,'叶') !== false; } $rs = new callbackfilteriterator($arrayiterator, 'isye'); print_r(iterator_to_array($rs)); /**outputarray( [0] => 叶2 [1] => 叶3 [2] => 叶4 [3] => 叶5 [4] => 叶6)**/
20. directoryiterator目录文件遍历器
directoryiterator::getsize
得到文件大小
directoryiterator::gettype
得到文件类型
directoryiterator::isdir
如果当前项是一个目录,返回true
directoryiterator::isdot
如果当前项是.或..,返回true
directoryiterator::isexecutable
如果文件可执行,返回true
directoryiterator::isfile
如果文件是一个常规文件,返回true
directoryiterator::islink
如果文件是一个符号链接,返回true
directoryiterator::isreadable
如果文件可读,返回true
directoryiterator::iswritable
如果文件可写,返回true
directoryiterator::key
返回当前目录项
directoryiterator::next
移动到下一项
directoryiterator::rewind
将目录指针返回到开始位置
directoryiterator::valid
检查目录中是否包含更多项
$it = new directoryiterator(../); foreach ($itas$file) { //用isdot ()方法分别过滤掉“.”和“..”目录 if (!$it->isdot()) { echo$file . \n; } }
21. recursivedirectoryiterator递归目录文件遍历器,可实现列出所有目录层次结构,而不是只操作一个目录。
recursivedirectoryiterator::getchildren
如果这是一个目录,为当前项返回一个迭代器
recursivedirectoryiterator::haschildren
返回当前项是否是一个目录而不是.或..
recursivedirectoryiterator::key
返回当前目录项的路径和文件名
recursivedirectoryiterator::next
移动到下一项
recursivedirectoryiterator::rewind
将目录指针返回到开始位置
recursiveiteratoriterator::current
访问当前元素值
recursiveiteratoriterator::getdepth
得到递归迭代的当前深度
recursiveiteratoriterator::getsubiterator
得到当前活动子迭代器
recursiveiteratoriterator::key
访问当前键
recursiveiteratoriterator::next
前移到下一个元素
recursiveiteratoriterator::rewind
将迭代器返回到顶级内层迭代器的第一个元素
recursiveiteratoriterator::valid
检查当前位置是否合法
//列出指定目录中所有文件 $path = realpath('../'); $objects = new recursiveiteratoriterator(new recursivedirectoryiterator($path), recursiveiteratoriterator::self_first); foreach ($objectsas$name => $object) { echo$name\n; }
22. filesystemiterator是directoryiterator的遍历器
$it = new filesystemiterator('../'); foreach ($itas$fileinfo) { echo$fileinfo->getfilename() . \n; }
23. globiterator带匹配模式的文件遍历器
//找出../目录中.php扩展名的文件 $iterator = new globiterator('./*.php'); if (!$iterator->count()) { echo'无php文件'; } else { $n = 0; printf(总计 %d 个php文件\r\n, $iterator->count()); foreach ($iteratoras$item) { printf([%d] %s\r\n, ++$n, $iterator->key()); } } /**output 总计 23 个php文件 [1] .\1.php [2] .\11.php [3] .\12.php [4] .\13.php [5] .\14.php [6] .\15.php [7] .\16.php [8] .\17.php [9] .\19.php [10] .\2.php [11] .\20.php [12] .\21.php [13] .\22.php [14] .\23.php [15] .\24.php [16] .\25.php [17] .\26.php [18] .\3.php [19] .\4.php [20] .\5.php [21] .\7.php [22] .\8.php [23] .\9.php **/
24. multipleiterator用于迭代器的连接器,具体看示例
$person_id = new arrayiterator(array('001', '002', '003')); $person_name = new arrayiterator(array('张三', '李四', '王五')); $person_age = new arrayiterator(array(22, 23, 11)); $mit = new multipleiterator(multipleiterator::mit_keys_assoc); $mit->attachiterator($person_id, id); $mit->attachiterator($person_name, name); $mit->attachiterator($person_age, age); echo连接的迭代器个数:.$mit->countiterators() . \n; //3 foreach ($mitas$person) { print_r($person); } /**outputarray( [id] => 001 [name] => 张三 [age] => 22)array( [id] => 002 [name] => 李四 [age] => 23)array( [id] => 003 [name] => 王五 [age] => 11)**/
25. recursivecallbackfilteriterator(php5.4)在recursiveiterator迭代器上进行递归操作,同时执行过滤和回调操作,在找到一个匹配的元素之后会调用回调函数。
function doesntstartwithlettert($current) { $rs = $current->getfilename(); return$rs[0] !== 't'; } $rdi = new recursivedirectoryiterator(__dir__); $files = new recursivecallbackfilteriterator($rdi, 'doesntstartwithlettert'); foreach (new recursiveiteratoriterator($files) as$file) { echo$file->getpathname() . php_eol; }
26. simplexmliteratorxml文档访问迭代器,可实现访问xml中所有节点
$xml = next()) { if (!array_key_exists($sxi->key(), $a)) { $a[$sxi->key()] = array(); } if ($sxi->haschildren()) { $a[$sxi->key()][] = sxitoarray($sxi->current()); } else { $a[$sxi->key()][] = strval($sxi->current()); } } return$a; } $xmliterator = new simplexmliterator($xml); $rs = sxitoarray($xmliterator); print_r($rs); /**outputarray( [book] => array ( [0] => array ( [title] => array ( [0] => php basics ) [author] => array ( [0] => jim smith ) ) [1] => xml basics ))**/
其它类似信息

推荐信息