-- Michael Higgins <[EMAIL PROTECTED]>
Khamneian, Mahtaj wrote:
[snip]I have a query that returns the following data from the db: ... operid emplid course -------- ---------- ---------...
Noting that different courses are associated with the same oprid and emplid, I need to format the output so that a single line is printed for each oprid. e.g., SSPT490 12050971 37290 38380 38540 52320
I have used both fetchall_arrayref() and fetchrow_array() methods to fetch the data. I can think of a quick and dirty way of doing this, but was looking for an efficient/elegant way.
Any/all help is appreciated.
Maybe push them onto a hashkey?
(untested)
my %results;
foreach (@$fetched){
push @{$results{$_->[0].' '.$_->[1]}}, $_->[2];
}
map {print "$_ @{$results{$_}}\n"} sort keys %results;
If the data can be sorted you can also just walk down the list, printing items until the first field changes:
local $\; local $,;
my $last = '';
for my $row ( @$rowz ) { if( $last ne $row->[0] ) { print "\n" if $last; print $last = $row->[0]; }
print join "\t" '', @{$row}[1,2]; }
print "\n";
i.e., print a newline if the last record has a different $row->[0] than this one, then the new row header. for each record print the fields pasted together with tabs and a leading tab separator.
The hash trick is necessary if your data is not sorted or if you have to accumulate it in one place to maniuplate it before printing the stuff.
Aside: You could modify the loop above for a speed gain by using fetchrow w/ bound values. That would leave you with something like "while( fetch... ){ ... }". If the list is non-trivial then sorting it and returning the rows singly may be less overhead (see the DBI book, DBI pod, and numerous postings of Tim's for examples of how to use the bound values).
enjoi
-- Steven Lembark 2930 W. Palmer Workhorse Computing Chicago, IL 60647 +1 888 359 3508