zoukankan      html  css  js  c++  java
  • 迭代器

    <?php
    
    /**
     * 迭代器
     * 使用php Iterator接口
     *
     * 迭代器在遍历大文件,或者大数据的时候很有用,因为它不需要将数据一次性取出,而是即取即用。
     * 使用yield生成器也可以实现相同效果。
     */
    class fileLineIterator implements Iterator {
        private $cur = NULL;
        private $nxt = NULL;
        private $lineCount = 0;
        
        public function __construct($filename) {
            $this->fp = fopen($filename, 'r');
        }
        
        //在每次迭代之前初始化某些操作
        public function rewind() {
            rewind($this->fp);
            $this->cur = fgets($this->fp);
            $this->nxt = fgets($this->fp);
            return true;
        }
        
        //获取当前元素的键
        public function key() {
            return $this->lineCount++;
        }
        
        //获取当前元素的值
        public function current() {
            return $this->cur;
        }
        
        //元素向前推一位
        public function next() {
            $this->cur = $this->nxt;
            $this->nxt = fgets($this->fp);
        }
        
        //通过该操作判断迭代是否应该结束
        public function valid() {
            return $this->cur===FALSE?FALSE:TRUE;
        }
    }
    
    $fileIter = new fileLineIterator('test_iterator.txt');
    
    foreach($fileIter as $line) {
        var_dump($line,$fileIter->current());
    }
  • 相关阅读:
    webpack 添加 jquery 插件
    openldap安装配置
    生成ssl证书
    vyos (三) HA
    vyatta的fork开源版本
    vyos (一) 基础配置
    iptable软路由
    keepalive实现web服务器active/passive
    docker学习(二)
    docker学习(一)
  • 原文地址:https://www.cnblogs.com/mtima/p/3181338.html
Copyright © 2011-2022 走看看