Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Collecting data in a recursive routine.

by chipmunk (Parson)
on Mar 07, 2002 at 04:38 UTC ( #149939=note: print w/replies, xml ) Need Help??


in reply to Collecting data in a recursive routine.

I see that you're fetching categories in groups, grabbing all the children of a specific category, then going on to the next parent category... My inclination would be to fetch all the categories at once, then organize them. Here's one way to do this:
my $cats_sth = $dbh->prepare(<<"EndOfSQL"); SELECT category_id, name, parent FROM $sql{categories} ORDER BY category_id ASC -- assumes parent id is always less than child id EndOfSQL my @cats; # build the data structure while (my($cat_id, $name, $parent_id) = $cats_sth->fetchrow_array()) { $cats[$cat_id] = [$name, $parent_id, []]; if ($cats[$parent_id]) { push @{$cats[$parent_id][2]}, $cat_id; } elsif ($parent_id) { warn "Parent $parent_id not found for category $cat_id '$name' +\n"; } } # print the categories foreach my $cat (@cats) { next unless $cat and !$cat->[1]; print_category($cat, \@cats, ''); } # recursively print a category and its children sub print_category { my($cat, $cats, $indent) = @_; print $indent, $cat->[0], "\n"; foreach my $child_id (@{$cat->[2]}) { print_category($cats->[$child_id], $cats, "$indent "); } }
The data structure that this uses is:
[ [ name, parent id, [ child ids ] ], [ name, parent id, [ child ids ] ], ... ]
where the ids are also the indexes into the array.

This probably is not the best data structure for your task, although it does get the job done. It should give you some ideas about solving the problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://149939]
help
Chatterbox?
[choroba]: They even sent me a letter whether I'd be willing to come to Milano to testify in the court
[choroba]: I replied with "yes" but the trial never happened
[Discipulus]: dont be so sure choroba.. 11 years is not too long for an Eatalian judgement
[choroba]: I've moved to Prague in the meantime, they can't reach me anymore :-)
[Discipulus]: Eataly: average 8years and 7months for all 3 degrees of judgement..

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2017-11-20 09:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (286 votes). Check out past polls.

    Notices?