【问题标题】:How to skip the current in php SPL iterator如何在 php SPL 迭代器中跳过当前
【发布时间】:2014-03-30 21:57:45
【问题描述】:

这对专家来说一定是个愚蠢的问题,但不知道该怎么做。

我有几千行的 csv,有些行是空的。当我实现 SPL Iterator 时,它也会返回空行,这会破坏我的 array_combine

我的问题是,我该怎么做才能使用迭代器跳过空行。

class CSVIterator implements Iterator {

const ROW_LENGTH = 4096;
/**
 * csv file path to load 
 * @var string
 */
private $_filePointer;

/**
 * @var array
 */
private $_currentElement;

/**
 * @var integer
 */
private $_rowCounter;

/**
 * @var string
 */
private $_delimiter;

/**
 * @param string $file        path of csv file
 * @param array  $columnNames optional column headings
 * @param string $delimiter
 */
public function __construct($file, $columnNames=array(), $delimiter=',') {
    if (! file_exists($file)) {
        throw new InvalidArgumentException("The file $file cannot be read", 1);
    }
    $this->_filePointer = fopen($file, 'r');
    $this->_delimiter = $delimiter;
    $this->_columnNames = $columnNames;
}

/**
 * get column headings for array keys
 * @return void
 */
function rewind() {
    $this->_rowCounter = 0;
    rewind($this->_filePointer);
    // get array keys
    if (empty($this->_columnNames)) {
        $this->_columnNames = fgetcsv($this->_filePointer, self::ROW_LENGTH, $this->_delimiter);
    } else {
        // skip the header row
        fgetcsv($this->_filePointer, self::ROW_LENGTH, $this->_delimiter);
    }


}

/**
 * create key value pair with column headings and csv rows
 * @return array
 */
function current() {
    $this->_currentElement = 
        fgetcsv($this->_filePointer, self::ROW_LENGTH, $this->_delimiter);
    $this->_rowCounter ++;
    $keyValue = array_combine($this->_columnNames, $this->_currentElement);
    return $keyValue;
}

/**
 * @return integer
 */
function key() {
    return $this->_rowCounter;
}

/**
 * check if end of file
 * @return boolean
 */
function next() {
    return ! feof($this->_filePointer);
}

/**
 * close file if EOF
 * @return boolean
 */
function valid() {
    if (! $this->next()) {
        fclose($this->_filePointer);
        return FALSE;
    }
    return TRUE;
}

}

【问题讨论】:

  • 您知道SplFileObject 类可以为您完成这项工作,包括解析CSV 和跳过空行吗?我建议看一下,而不是自己重新实现它。

标签: php loops iterator spl


【解决方案1】:

我实际上发现SPL Filter Iterator 可以为我做到这一点。 这是一个抽象类,它有一个抽象的accept 方法

public abstract bool accept ( void )

我可以在其中指定我的条件以跳过current

【讨论】:

    猜你喜欢
    • 2011-06-28
    • 2012-07-06
    • 2011-08-06
    • 2023-03-24
    • 2013-03-30
    • 1970-01-01
    • 2017-08-03
    • 2021-09-16
    • 2022-01-22
    相关资源
    最近更新 更多