SPL(2)--- ArraryIterator迭代器

SPL(2)— ArraryIterator迭代器

1.介绍老友

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


2.Time To 实战
  • bkduck在此先贴上代码,具体分析说明在代码结束处!!!
  • DEMO:
<?php 
//探究:ArrayIterator offsetUnset后 默认不再用该index,使用最后index
class 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值