Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Creating a tree from a parent child list, that also includes node specific properties...

by ikegami (Patriarch)
on Jun 29, 2009 at 15:25 UTC ( [id://775711]=note: print w/replies, xml ) Need Help??


in reply to Creating a tree from a parent child list, that also includes node specific properties...

use strict; use warnings; use DBI; sub treeify { my ($sth) = @_; my %root = ( _children => [] ); my %children; while (my $row = $sth->fetchrow_hashref()) { my ($id, $parent_id) = @$row{qw( Child Parent )}; my $parent = ( defined($parent_id) ? $children{$parent_id} ||= { _children => [] } : \%root ); my $node = $children{$id} ||= {}; %$node = ( _children => [], %$row ); push @{ $parent->{_children} }, $node; } return \%root; } { my $sponge = DBI->connect( 'dbi:Sponge:', '', '', { RaiseError => 1 } ); my $sth = $sponge->prepare( 'SELECT * FROM Fruit', { NAME => [qw( Parent Child Desc Property1 +Property2 )], rows => [ [ undef, 50, 'Fruit', 'hidden', +'non-searchable' ], [ 50, 100, 'Apple', 'hidden', +'non-searchable' ], [ 100, 110, 'Granny Smith', 'Visible', +'searchable' ], ], } ); my $tree = treeify($sth); use Data::Dumper; print Dumper $tree; }

Based on Generating a Hash of Hashes Recursively to Display Database Hierarchy. Should use a classes.

  • Comment on Re: Creating a tree from a parent child list, that also includes node specific properties...
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://775711]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-25 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found