Re: recursion question
| From: | Dean Hall | Date: | Wed, 30 Aug 2000 16:42:55 +0000 |
| Subject: | Re: recursion question | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-14432@lists.php.net to get a copy of this message | ||
On Wed, 30 Aug 2000, Robert J. Cissell wrote:
> I'm trying to write my first recursive function but I'm not doing too well. I have a
> mysql database with the fields of topic_id, topic_name, and parent_topic_id. If I have a topic_id
> with a parent_topic_if of 5, I want the function to get the topic_name and parent_topic_id for 5,
> and again and again until it reaches a parent_topic_id of 0, which would be my top level. As it
> goes, it would store these values in an array which I can run through later to build a path from the
> top to whatever topic_id i started out at. What I can't figure is how to set up the recursive
> function to do so. I have no problem with the database stuff, but I need help with the function
> stuff. Any ideas or suggestions are greatly appreciated.
>
> Robert Cissell
>
In this case, and in most cases in a production environment, I would stay
away from recursion unless you know exactly what you're doing; anything
you can do recursively you can also do iteratively.
My suggestion is to use a while loop in this case and store the path as
you go.
In any case, for any recursive function, you need a base case -- the thing
you're looking for at the end of the recursion; and then you need a
recursive call.
For instance, I have a site tree object which is a real n-ary tree. Here's
how I get the path for a node.
function rec_getPath($node) {
// base case - level 0 - root of the tree
if($node->level == 0) {
return $node->getPath();
}
// recursive case -- get the parent's path and then node's path.
return $node->getParent()->getPath() . $node->getPath();
}
Dean Hall.