ArrayIterator迭代器遍历数组
来源:互联网 发布:软件销售工作好么 编辑:程序博客网 时间:2024/05/22 08:07
代码
<?phpnamespace app\index\controller;use ArrayObject;//引入迭代器class Index{ public function index() { $fruits = array( "apple" => 'apple value',//position =0 "orange" => 'orange value',//position =1 "grape" => 'grape value', "plum" => 'plum value', ); dump($fruits); echo '------------------普通数组遍历-----------------'."<br/>"; foreach ($fruits as $key => $value) { echo $key.":".$value."<br/>"; } echo '------------------使用ArrayIterator迭代器遍历数组(foreach)-----------------'."<br/>"; $obj = new ArrayObject($fruits);//创建数组对象 $it = $obj->getIterator();//获取迭代器 foreach ($it as $key => $value) { echo $key.":".$value."<br/>"; } echo '------------------(while)-----------------'."<br/>"; $it->rewind();//如果要使用current必须使用rewind while ($it -> valid()) { echo $it->key().":".$it->current()."<br/>"; $it -> next(); } echo '------------------跳过某些元素进行打印(while)-----------------'."<br/>"; $it->rewind(); if($it->valid()){ $it -> seek(1);//当前指针指向position=1 while ($it -> valid()) { echo $it->key().":".$it->current()."<br/>"; $it -> next(); } } echo '------------------用迭代器的key进行排序(ksort)-----------------'."<br/>"; $it->ksort(); foreach ($it as $key => $value) { echo $key.":".$value."<br/>"; } echo '------------------用迭代器的value进行排序(asort)-----------------'."<br/>"; $it->asort(); foreach ($it as $key => $value) { echo $key.":".$value."<br/>"; } } }
运行结果
array(4) { ["apple"] => string(11) "apple value" ["orange"] => string(12) "orange value" ["grape"] => string(11) "brape value" ["plum"] => string(10) "plum value"}------------------普通数组遍历-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------使用ArrayIterator迭代器遍历数组(foreach)-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------(while)-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------跳过某些元素进行打印(while)-----------------orange:orange valuegrape:brape valueplum:plum value------------------用迭代器的key进行排序(ksort)-----------------apple:apple valuegrape:brape valueorange:orange valueplum:plum value------------------用迭代器的value进行排序(asort)-----------------apple:apple valuegrape:brape valueorange:orange valueplum:plum value
阅读全文
0 0
- ArrayIterator迭代器遍历数组
- php标准库 SPL 迭代器之 ---------ArrayIterator(数组迭代)
- php标准库(SPL)-迭代器-AppendIterator和ArrayIterator详解
- 集合Set迭代器遍历和数组遍历
- 数组遍历 和 迭代器遍历的区别
- C++使用迭代器遍历数组
- 遍历数组
- 遍历数组
- 数组遍历
- 遍历数组
- 遍历数组
- 遍历数组
- 遍历数组
- 数组遍历
- 遍历数组
- 遍历数组
- 遍历数组
- 遍历数组
- web访问的原理
- centos7下redis莫名的链接不上
- 工厂模式
- GitHub管理代码操作方式
- 迷茫的5年
- ArrayIterator迭代器遍历数组
- Android recovery UI实现分析
- Netty4.0学习笔记系列之一:Server与Client的通讯
- 隔离见证是什麽? 为什麽我们必须尽快实行?
- Ant标签详解
- ajax异步调用
- javaseday29(tcp)
- node request(api文件下载时用到)
- 做程序员有哪些好处?