Recursive Parent / Child

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Turv
Forum Commoner
Posts: 25
Joined: Fri Mar 13, 2009 3:56 pm

Recursive Parent / Child

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Recursive Parent / Child

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Turv
Forum Commoner
Posts: 25
Joined: Fri Mar 13, 2009 3:56 pm

Re: Recursive Parent / Child

Post 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,
Turv
Forum Commoner
Posts: 25
Joined: Fri Mar 13, 2009 3:56 pm

Re: Recursive Parent / Child

Post by Turv »

Just wonder if anyone has a solution for this?

Thanks.
Post Reply