[英]How to skip the current in php SPL iterator
It must be a silly questions for experts but can't figure out how. 对于专家来说,这肯定是一个愚蠢的问题,但却无法弄清楚如何做到。
I have a csv of couple of thousands rows and some rows are empty. 我有几千行的csv,有些行是空的。 As I am implementing SPL
Iterator
it returns me the null rows as well, which breaks my array_combine
. 在实现SPL
Iterator
它也会向我返回空行,这会破坏我的array_combine
。
My question is, what can I do to skip the empty rows using the Iterator. 我的问题是,我该怎么做才能使用Iterator跳过空行。
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;
}
} }
I actually figured out SPL Filter Iterator can do that for me. 我实际上发现SPL筛选器迭代器可以为我做到这一点。 This is an abstract class which has an abstract
accept
method 这是一个抽象类,具有抽象的
accept
方法
public abstract bool accept ( void )
where I can specify my criteria to skip current
. 在这里我可以指定我的条件以跳过
current
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.