nozavroni / csvelte

🕺🏻 CSV and Tabular Data library for PHP
http://phpcsv.com/
Other
6 stars 0 forks source link

Need CSVelte::import or Reader::asArray method (or both) #105

Closed nozavroni closed 7 years ago

nozavroni commented 7 years ago

Probably the most common use case for CSVelte would be somebody that simply needs to read a CSV file into a PHP array. Currently, CSVelte has no simple way of doing that. This is how you would read a CSV file into an array with CSVelte (as-is):

<?php
$stream = new IO\Stream('./data/foos.csv');
$flavor = new Flavor(['delimiter' => "\t", 'lineTerminator' => "\n"]);
$reader = new Reader($stream, $flavor);
$array = [];
foreach ($reader as $line_no => $row) {
    $array []= $row->toArray();
}
// now, after 7-8 lines of code, at a minimum, we finally have our $array
// that is a LOT of keystrokes for such a simple task... 

Possible solutions

Add a CSVelte::import($filename, $flavor) method

Could also be called importToArray() or readToArray() or getAsArray(), but the point is, this would be the counter to the CSVelte::export() method. It would do, basically, the opposite. Read a CSV source, and produce a PHP array.

<?php
$csv_arr = CSVelte::import('./data/bars.csv', ['delimiter' => "\t", 'lineTerminator' => "\n"]);

Add a Reader::asArray() method

Could also be called toArray() or buildArray() or any number or other names. But the point is, you wouldn't have to traverse the file/dataset manually just to produce a simple array.

<?php
$csv_arr = CSVelte::reader('./data/bars.csv', ['delimiter' => "\t", 'lineTerminator' => "\n"])->asArray();
nozavroni commented 7 years ago

I'm going to go with the latter solution for now. If I find that people are expecting a CSVelte::import() method just because there's a CSVelte::export(), then maybe I'll consider adding it. But I want to be careful about just adding random methods in the library as a whole, but especially within the CSVelte class. I do not want that class to become cluttered and ridiculous.

nozavroni commented 7 years ago

Added to version 0.2... needs documentation and unit testing too...

nozavroni commented 7 years ago

Fixed, tested, documented.