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;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|