Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Collecting data in a recursive routine.

by beppu (Hermit)
on Mar 07, 2002 at 05:45 UTC ( #149952=note: print w/replies, xml ) Need Help??

in reply to Collecting data in a recursive routine.

DISCLAIMER: I have not tried this code out, but I think it will work. All I know is that :perl -wc doesn't complain. Let me know what happens.

If it works I will be happy, because I've been away from Perl for a long time, and I'm trying to shake off some rust. Even if it doesn't work, it's got to be close. Anyway:

$tree = GetCategories($node)

# # # # # # #' . . `# # i # making an ass out of u and me since 1975 # assumptions # #+_. ._+# my %sql; # is filled w/ names of tables that hold category data my $dbh; # database handle =head2 The Structure of a Node { id => $number, name => $string, children => $array_ref_of_more_nodes, } =head2 Usage To get the whole tree: my $tree = GetCategories(); To get a partial tree, pass in a hashref that has an C<id> key representing the parent C<category_id> to start with: my $subtree = GetCategories($starting_node); =cut sub GetCategories { my $node = shift || undef; my $select_children = "SELECT category_id,name FROM $sql{categories} "; # Create the root node only on the 1st time through, # and complete the SQL statement for # selecting all the nodes children. if (not defined $node) { $node = { id => 0, name => '/', children => [ ], }; $select_children .= "WHERE parent IS NULL"; } else { $select_children .= "WHERE parent=$node->{id}"; } # Find all the children of the current node. my $all_cats = $dbh->selectall_arrayref($select_children); my $c; # Add each child to $node->{children}, and # then recursively add get each child's children foreach $c (sort { $a->[1] cmp $b->[1] } @{$all_cats}) { my $child_node = { id => $c->[0], name => $c->[1], children => [ ], }; # ............. depth-first style ..... push @{$node->{children}}, $child_node; GetCategories($child_node); } return $node; }

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2021-09-17 05:14 GMT
Find Nodes?
    Voting Booth?

    No recent polls found