• php设计模式-迭代器


    class CustomIterator implements Iterator
    {
        private $_data;
        private $_index = 0;
    
        public function __construct($data)
        {
            $this->_data = $data;
        }
    
        /**
         * 返回当前指针指向的元素
         * @return mixed
         */
        public function current()
        {
            return $this->_data[$this->_index];
        }
    
        /**
         * 指针向前推一位
         */
        public function next()
        {
            $this->_index ++;
        }
    
        /**
         * 重置指针,将指针指向第一个元素
         */
        public function rewind()
        {
            $this->_index = 0;
        }
    
        /**
         * 返回当前指针位置
         * @return int|mixed
         */
        public function key()
        {
            return $this->_index;
        }
    
        /**
         * 检测指针当前指向是否有效
         * @return bool
         */
        public function valid()
        {
            return count($this->_data) > $this->_index;
        }
    }
    
    $data = array(
        ['name' => 'zhangsan', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'lisi', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'waner', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'faguan', 'age' => 12, 'career' => 'engineer'],
    );
    
    $obj = new CustomIterator($data);
    
    echo '<pre>';
    foreach ($obj as $key => $user) {
        print_r($user);
    }
    
    echo '---------------------------------------------------<br>';
    // 重置指针,相当于数组里的reset()方法
    $obj->rewind();
    
    while ($obj->valid())
    {
        print_r($obj->current());
        $obj->next();
    }
    

      结果:

    Array
    (
        [name] => zhangsan
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => lisi
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => waner
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => faguan
        [age] => 12
        [career] => engineer
    )
    ---------------------------------------------------
    Array
    (
        [name] => zhangsan
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => lisi
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => waner
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => faguan
        [age] => 12
        [career] => engineer
    )
    

      

  • 相关阅读:
    【字符串/广搜】P1032 字串变换
    【动态规划】P1541 乌龟棋
    【动态规划/递归】(团队内部比赛试题)T134293 T2.货币系统问题
    Redis-事务
    Redis-Pipeline
    Redis-通过前缀获取所有key
    Spring 三级缓存
    TopK_LRU_归并

    如何从一亿个数组里找出最大的十个
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13353295.html
Copyright © 2020-2023  润新知