while ($row = $sth->fetchrow_arrayref){ if (!defined($objects{$row->[0]})) ## not seen this object before, so add it to the hash { $objects{$row->[0]} = $row->[1]; }else{ $objects{$row->[0]} = $objects{$row->[0]}.','.$row->[1]; ## seen this object so append to csv } } while ($header_row=$header_sth->fetchrow_arrayref){ $headers .= "\"$header_row->[1]\"".','; } print $headers,"\n"; while (($k,$v)=each(%objects)){ print $v,"\n"; }