Parsing CSV files

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hello All,

I have to convert a csv with multiple rows per individual name per
data into a csv with a single row per individual name with data strung
out in additional columns as needed.




My initial thought is to loop through the file doing a name match then
coping data into another file.  However I am not certain how best to
proceed or even if this is the best or most appropriate method.

I would appreciate hearing some discussion about this.


Re: Parsing CSV files

sixlead wrote:
Quoted text here. Click to load it

Personally, I'd create an array and then run through the file, adding
each new name as a string key which is linked to an array containing the
data for that name, so that it would end up like:

$myarray["bob"] == ["2005", "2006", "2007"].

Then I'd loop through the array dumping each key and the contents of its
  subarray onto one line in the output file.

That way, you only have to scan through the input file once, and you can
dump the whole output file in one go as well. I guess it all depends
whether RAM or disk usage is your main concern.


Re: Parsing CSV files

sixlead wrote:
Quoted text here. Click to load it

If the file isn't too big, I'd just use fgetcsv() to get the entire file
into a two dimensional array.  Then go through that array and build a
second array.  Key would be the name, and the value would be an array
containing the matching values, i.e.

After fgetcsv():

   Array {
     [0] => Array {
        [0] => 'bob'
        [1] => 2005
     [1] => Array {
        [0] => 'bob'
        [1] => 2006
     [2] => Array {
        [0] => 'bob'
        [1] => 2007

After massaging the data:

   Array {
     ['bob'] => Array {
       [0] => 2005
       [1] => 2006
       [2] => 2007

Then it's a simple job to go through the second array and build the
output in the way you want.

This has advantages that you can have any number of entries for each
name, and the names don't have to be in any particular order.

Of course, if the file is too big, this won't work.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Site Timeline