in reply to A list of parents and children. How to make a tree?
First I added one person (Jim Morris) to have three levels in your data:
my $input = { 'Sally Smith' => { parents => ['Bob Smith', 'Rhonda Smith']}, 'Betty Freeman' => { parents => ['Earl Freeman', 'Harmony Ellis']} +, 'Betty Boop' => { parents => ['Rhonda Smith', 'Louis McFern']}, 'Jim Morris' => { parents => ['Betty Boop', 'John Wayne']}, };
You wrote that you want to descent from top, so I made new structure with children relationships and listing all people:
my $people = {}; for my $m (keys %$input) { add_person($people,$m, parents => $input->{$m}{parents}); for my $p (@{ $input->{$m}{parents} }) { add_person($people,$p,children => $m); } } sub add_person { my ($people,$name,%params) = @_; if(! defined $people->{$name}) { $people->{$name} = { children => [], parents => [] }; } for my $par (keys %params) { push @{ $people->{$name}{$par} }, ref($params{$par}) eq "ARRAY" ? @{$params{$par}} : $params +{$par}; } }
The $people structure dumped:
{ "Betty Boop" => { children => ["Jim Morris"], parents => ["Rhond +a Smith", "Louis McFern"], }, "Betty Freeman" => { children => [], parents => ["Earl Freeman", "Ha +rmony Ellis"] }, "Bob Smith" => { children => ["Sally Smith"], parents => [] }, "Earl Freeman" => { children => ["Betty Freeman"], parents => [] }, "Harmony Ellis" => { children => ["Betty Freeman"], parents => [] }, "Jim Morris" => { children => [], parents => ["Betty Boop", "John + Wayne"] }, "John Wayne" => { children => ["Jim Morris"], parents => [] }, "Louis McFern" => { children => ["Betty Boop"], parents => [] }, "Rhonda Smith" => { children => ["Sally Smith", "Betty Boop"], pare +nts => [] }, "Sally Smith" => { children => [], parents => ["Bob Smith", "Rhond +a Smith"] }, }
Now you can start with people not having any parents and recurse over children.
for my $top_level (sort keys %$people) { next if @{ $people->{$top_level}{parents} }; print_level($people,$top_level,0); } sub print_level { my ($people,$name,$level) = @_; print " "x$level,$name,"\n"; for my $child (@{ $people->{$name}{children} }) { print_level($people,$child,$level+1); } }
It produces this tree using indentation:
Bob Smith Sally Smith Earl Freeman Betty Freeman Harmony Ellis Betty Freeman John Wayne Jim Morris Louis McFern Betty Boop Jim Morris Rhonda Smith Sally Smith Betty Boop Jim Morris
Is this what you expected to see? If yes, producing some kind of javascript tree should be quite easy.
-- Roman
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: A list of parents and children. How to make a tree?
by tejinashi (Initiate) on Jan 03, 2010 at 10:44 UTC |