diff options
author | ignace nyamagana butera <nyamsprod@gmail.com> | 2014-11-28 18:07:37 +0100 |
---|---|---|
committer | ignace nyamagana butera <nyamsprod@gmail.com> | 2014-11-28 18:07:37 +0100 |
commit | 28eabada4d2ccefc272b506dbcf1d6e9ebab9b06 (patch) | |
tree | 44ea059f8733b2813f76889555dbd96a18c52a8a | |
parent | 539230130d2bf9f548ac0a49a306a08dc0dfec85 (diff) | |
parent | 54b1ce617f5c8249b84caa2166cebfc2a7b03059 (diff) | |
download | csv-28eabada4d2ccefc272b506dbcf1d6e9ebab9b06.zip csv-28eabada4d2ccefc272b506dbcf1d6e9ebab9b06.tar.gz csv-28eabada4d2ccefc272b506dbcf1d6e9ebab9b06.tar.bz2 |
Merge pull request #63 from RobinDev/master
Add default keys when keys are not set when use Reader::fetchAssoc()
-rw-r--r-- | src/Reader.php | 30 | ||||
-rw-r--r-- | test/ReaderTest.php | 9 |
2 files changed, 38 insertions, 1 deletions
diff --git a/src/Reader.php b/src/Reader.php index 03221aa..5b9f23b 100644 --- a/src/Reader.php +++ b/src/Reader.php @@ -38,6 +38,12 @@ class Reader extends AbstractCsv protected $stream_filter_mode = STREAM_FILTER_READ; /** + * Contain the header (csv first line) + * @var array + */ + protected $header; + + /** * Return a Filtered Iterator * * @param callable $callable a callable function to be applied to each Iterator item @@ -133,8 +139,12 @@ class Reader extends AbstractCsv * * @return array */ - public function fetchAssoc(array $keys, callable $callable = null) + public function fetchAssoc(array $keys = [], callable $callable = null) { + if (empty($keys)) { + $keys = $this->getDefaultKeys(); + } + $validKeys = array_unique(array_filter($keys, function ($value) { return self::isValidString($value); })); @@ -154,6 +164,24 @@ class Reader extends AbstractCsv } /** + * Get the first line and add a filter to not get it again when + * fetching. + * + * @return array + */ + protected function getDefaultKeys() + { + if (isset($this->header)) { + return $this->header; + } + + $this->header = $this->fetchOne(); + $this->addFilter(function ($row, $index) { return $index > 0; }); + + return $this->header; + } + + /** * Intelligent Array Combine * * add or remove values from the $value array to diff --git a/test/ReaderTest.php b/test/ReaderTest.php index 36d4dc1..47e38fb 100644 --- a/test/ReaderTest.php +++ b/test/ReaderTest.php @@ -286,4 +286,13 @@ EOF; $csv = Reader::createFromPath(__DIR__.'/foo.csv')->newWriter('a+'); $this->assertInstanceOf('\League\Csv\Writer', $csv); } + + public function testFetchAssocWithoutKeys() + { + $csv = Reader::createFromPath(__DIR__.'/data/prenoms.csv'); + $csv->setDelimiter(';'); + $csv->setEncodingFrom("iso-8859-15"); + $data = $csv->fetchAssoc(); + $this->assertTrue($data[0]['prenoms'] == 'Aaron'); + } } |