in reply to Generating a Hash of Hashes Recursively to Display Database Hierarchy
If you're ok with changing
return unless ref($hashref) eq 'HASH';
to
return unless keys %$hashref;
then you can use the following:
sub treeify { my ($sth) = @_; my %root; my %children; while (my $row = $sth->fetch()) { my ($id, $parent_id) = @$row; my $parent = ( defined($parent_id) ? $children{$parent_id} ||= {} : \%root ); $parent->{$id} = $children{$id} ||= {}; } return \%root; }
Test:
{ my $sponge = DBI->connect( 'dbi:Sponge:', '', '', { RaiseError => 1 } ); my $sth = $sponge->prepare( 'SELECT id, parent_id FROM Table', { NAME => [qw( id parent_id )], rows => [ [ a => undef ], [ b => 'a' ], [ d => 'c' ], [ c => 'b' ], [ e => 'a' ], ], } ); my $tree = treeify($sth); use Data::Dumper; print Dumper $tree; }
Output:
$VAR1 = { 'a' => { 'e' => {}, 'b' => { 'c' => { 'd' => {} } } } };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generating a Hash of Hashes Recursively to Display Database Hierarchy
by c4onastick (Friar) on Jun 23, 2009 at 15:17 UTC | |
by ikegami (Patriarch) on Jun 23, 2009 at 16:23 UTC | |
by c4onastick (Friar) on Jun 23, 2009 at 16:59 UTC | |
by ikegami (Patriarch) on Jun 23, 2009 at 17:17 UTC |