SPL(2)--- ArraryIterator迭代器

来源:互联网 发布:淘宝ralph lauren 编辑:程序博客网 时间:2024/05/16 05:49

SPL(2)— ArraryIterator迭代器

1.介绍老友

说实话,Iterator很多,但ArraryIterator也算是日常使用比较多的一种迭代器,++它主要针对是数组迭代++,其继承Interface有 ArrayAccess、SeekableIterator、 Countable、 Serializable!下面bkduck将通过讲解一个关于插入append的index索引问题,希望能让自己熟悉ArraryIterator的基本使用


2.Time To 实战
  • bkduck在此先贴上代码,具体分析说明在代码结束处!!!
  • DEMO:
<?php //探究:ArrayIterator offsetUnset后 默认不再用该index,使用最后indexclass MyArrIterator extends ArrayIterator{    public function __construct($array){        parent::__construct($array);    }    //append & $myArrIterator[2]='' 会触发    public function offsetSet($index, $newval){        if(is_null($index)){ //append            $index = $this->appendOffsetSet($newval);        }        parent::offsetSet($index, $newval);         $this->ksort(); //按值排序    }    //append 触发 offsetSet index索引为null    public function appendOffsetSet($newval){        $index = 0; //count($this)        while($this->offsetExists($index)){            $index++;        }        return $index;    }}$arrList = array('bkduck01','bkduck02','bkduck03');$myArrIterator = new MyArrIterator($arrList);$arrIterator = new ArrayIterator($arrList);//与append不同,传入index$myArrIterator['test'] = 'test';$arrIterator['test'] = 'test';//删除第二个$myArrIterator->offsetUnset(1);$arrIterator->offsetUnset(1);//验证ArrayIterator 在index=1插入 or last insert$myArrIterator->append('bkduck04');$arrIterator->append('bkduck04');// $myArrIterator->append(array('nn'=>'222'));// $arrIterator->append(array('nn'=>'222'));var_dump($arrIterator->serialize());var_dump($myArrIterator->serialize());echo '<br/>-----$myArrIterator:------- <br/>';print_r($myArrIterator);echo '<br/>-----$arrIterator:------- <br/>';print_r($arrIterator);?>
  • 探究:ArrayIterator 调用offsetUnset(index),append(val) 默认不再用该index,使用最后index
  • 分析:MyArrIterator是自定义的类,继承ArrIterator,主要为了对比,重定义了offsetSet()函数(offsetSet调用append会触发该函数)!试验开始,分别使用一个含3个值得数组实例化它们,然后使用offsetUnset(1),参数为需要删除的索引值,再使用append(‘bkduck04’),观察它们究竟在index=1 OR index=3(last index)插入值。最后发现ArrIterator在index=3插入,而MyArrIterator在index=1处插入,因为MyArrIterat重定义offsetSet时,插入是从0遍历,使用offsetExists(),一旦有空位就插入。
  • 总结:ArraryIterator使用并不难,完全和数组一样,还有一个序列化,和一般的序列化函数一样,比较简单!serialize()
0 0
原创粉丝点击