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' => {} } } } };
In reply to Re: Generating a Hash of Hashes Recursively to Display Database Hierarchy
by ikegami
in thread Generating a Hash of Hashes Recursively to Display Database Hierarchy
by c4onastick
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |