Although it might not be the most efficient solution, this sounds like a job for recursion. First get all the top_level categories. Then loop through each one getting the children of that category.
# this assumes that you have the top level categories with a # parent_id that is NULL my $sql = qq~SELECT category_id, parent_id, category_name FROM ss_catalog_categories~ WHERE parent_id IS NULL; my $sth = $dbh->prepare($sql); $sth->execute; my $results = $sth->fetchall_arrayref({}); my $categories = format_results( $results ); sub format_results { my $results = shift; foreach my $result (@$results) { my $children = get_childrent($result->{category_id}); my %category = ( name => $result->{category_name}, children => $children, ); push(@$categories, \%category); } } sub get_children { my $parent = shift; my $sql = qq~SELECT category_id, parent_id, category_name FROM ss_catalog_categories~ WHERE parent_id IS ?; my $sth = $dbh->prepare($sql); $sth->execute($parent); return format_results($sth->fetchall_arrayref({})); }
This should at least give you an idea to go on - remember, this code is untested, but I've used the same idea before lots of times.

In reply to Re: Nested Categories by mpeters
in thread Nested Categories by spaceout

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.