Jump to content

Using recursion to find a parent? Suggestions orther than recursion?


John W.
 Share

Recommended Posts

Working on a project where I have different categories of Departments, under departments I have Offices, and each office has multiple pages.

DEPARTMENTS

     HUMAN RESOURCES

          About Human Resources
          Job Listings
               job 1 details page
               job 2 details page

     ADMINISTRATION

         About Administration
         Meet the Administrator

-----------------------------

stored in HUMAN RESOURCES is a background image and title of the department.

Instead of creating a background image for each office page (and it's sub pages like job 1 details page), I'm using the background image stored in HUMAN RESOURCES for all the child pages.

I'm familiar with using $page->rootParent, however, this will return DEPARTMENTS rather than the office, e.g. HUMAN RESOURCES that each sub page belongs to.

I thought about using a recursive function to traverse from the current page, when it reaches the template "office". Basically, if I'm in job 1 details page, it would traverse back up the tree until it reaches "office" template, such as "HUMAN RESOURCES".

Has anyone done something similar, but, using a built in method that I'm missing?

Thanks.

 

 

 

 

Link to comment
Share on other sites

Yeah, tried that, it pulls the first child under DEPARTMENTS

This doesn't work when you have several departments such as

DEPARTMENTS

     HUMAN RESOURCES

            About HR

            Job Listings

                      Job 1

                      Job 2

     ADMINISTRATION

            About Administration

    EMERGENCY OPERATIONS

            About Emergency Operations

 

In the case above, your suggestion would always return "Human Resources"

Link to comment
Share on other sites

I think I found a quick solution:

# cycles through all the current $page parents then
# returns the parent that is #x in the list
# $page is the current page, $parentNumber is the 
# parent to find and return in the tree

function getParent($page, $parentNumber) {
   $cnt=0;

   foreach($page->parents() as $p) {
    $cnt++;
     if($cnt == $parentNumber) {
          return $p;
      }
     }
     return false;
}

 #pass the current $page and return its third parent

 $parentPage = getParent($page,3);
 echo $parentPage->title;

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...