Skip to content

Instantly share code, notes, and snippets.

@anthonysterling
Created July 22, 2010 10:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonysterling/485810 to your computer and use it in GitHub Desktop.
Save anthonysterling/485810 to your computer and use it in GitHub Desktop.
<?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());
}
}
@graindeweb
Copy link

Hi,

Thanks for this gist. But function count() seems to not work this object: it always return 1.
Could you explain me why ?

Thanks

EDIT : I've found iterator_count()...

@anthonysterling
Copy link
Author

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. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment