Page 1 of 1

Recursive Parent / Child

Posted: Thu Sep 03, 2009 3:58 am
by Turv
Hi,

The topic title may not be very clear but hopefully i can explain it better.

I have a table of pages, and a field for Parent ID, If a page has no parent, the Parent ID is 0, and obviously if a Page has a Parent, the Parent ID is the id of that page.

Example Data
ID: 1, Page: Home, Parent ID: 0, url: home
ID: 2, Page: Sub-page, Parent ID: 1, url: sub-page

Now the situation i have is, I select a page (Sub-Page), which has an ID of 2, and what i want to do is have a function that can generate a url for this.

So if i gave this function an ID of 2, it will return home/sub-page, so if will recursively go through all the Parent ID's, retaining their url until there are no more parents and then return the url.

So if Sub-page(2) had a further child page called Sub-Sub-Page (ID 3), then it will return home/sub-page/sub-sub-page/

I'm not sure on how to approach this, and hoping someone can help me out.

Thanks.

Re: Recursive Parent / Child

Posted: Thu Sep 03, 2009 10:18 am
by pickle
How do you want to handle situations where a page has multiple children?

I've done something very similar to this for a CMS I built, but in reverse to how you're asking. Given an ID, I've walked up the parent/child relationship to build the URL for the asked page.

Re: Recursive Parent / Child

Posted: Thu Sep 03, 2009 10:41 am
by Turv
pickle wrote:How do you want to handle situations where a page has multiple children?

I've done something very similar to this for a CMS I built, but in reverse to how you're asking. Given an ID, I've walked up the parent/child relationship to build the URL for the asked page.
I think that's exactly what i'm after. The above was just an example and there may be multiple children which is why i assume it has to be some form of recursive function that will basically walk up the relationships to build the url.

If that makes sense..

Thanks,

Re: Recursive Parent / Child

Posted: Mon Sep 07, 2009 6:00 am
by Turv
Just wonder if anyone has a solution for this?

Thanks.