Created
July 22, 2010 10:21
-
-
Save anthonysterling/485810 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Iterates over a CSV file using the first | |
* row (column names) as the array keys for | |
* each subsequent entry returned | |
*/ | |
class AssociativeCsvFileIterator extends FilterIterator | |
{ | |
protected | |
/** | |
* @var array | |
*/ | |
$_keys = array(), | |
/** | |
* @var integer | |
*/ | |
$_count = 0; | |
/** | |
* @param string $file_name The file to read | |
* @param string $delimiter The field delimiter (one character only) | |
* @param string $enclosure The field enclosure character (one character only) | |
* @param string $escape The field escape character (one character only) | |
*/ | |
public function __construct($file_name, $delimiter = ',', $enclosure = '"', $escape = '\\'){ | |
$csv = new SplFileObject($file_name); | |
$csv->setFlags(SplFileObject::READ_CSV); | |
$csv->setCsvControl($delimiter, $enclosure, $escape); | |
$this->_keys = array_values($csv->current()); | |
$this->_count = count($this->_keys); | |
parent::__construct(new LimitIterator($csv, 1)); | |
} | |
/** | |
* @return array | |
*/ | |
public function current(){ | |
return array_combine( | |
$this->_keys, | |
parent::current() | |
); | |
} | |
/** | |
* @return boolean | |
*/ | |
public function accept(){ | |
return $this->_count === count(parent::current()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't implement the Countable interface, see http://www.php.net/~helly/php/ext/spl/classFilterIterator.html. Yep, http://php.net/manual/en/function.iterator-count.php is an option; good catch. :)