【发布时间】: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 和跳过空行吗?我建议看一下,而不是自己重新实现它。