# 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({})); }