For trivial tree-processing problems, a recursive solution is generally easiest. This might not be the best way if your tree is truly gigantic, but it should work in most cases. This is untested but should get you on the right track:
my $dbh = ... # set up database
sub display_groups {
my ( $parent, $level ) = @_;
# get all children of this parent
my $sth = $dbh->prepare("SELECT id, gname
FROM groups WHERE subgroup=?
ORDER BY gname");
$sth->execute( $parent );
# display each child and its descendants
while( my $row = $sth->fetchrow_hashref ) {
print " " x $level; # indent
print $row->{gname}, "\n";
display_groups( $row->{id}, $level + 1 );
}
}
# start with children of group 0
display_groups( 0, 0 );
Update: Added ORDER BY clause.
-
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.
|