Tag Archives: Recusion

How to get the top most parent ( parent’s parent ) Recursively in php , when to use Recursive Function

My table Structure:

id parent_id menu name
1 0 Home
2 0 Gallery
3 0 Message
4 3 From Principal
5 3 From Guardian
6 2 Events
7 2 Students
8 6 Picnic
9 6 Sports

Major Requirement:

Input : 9 (Sports->Events->Gallery Bottom Up Parent Wise)

output: 2 (Gallery->Events->Sports Top Down )

Our Requirement is to make the function that will return us the top most parent of any menu item. Lets say i need to find the parent of Sports (id=9) menu which is simple i.e. the menu name with id 6 i.e. Events

Simply we will write the simple query: select menu_name from table_name where id=6

But it is not as simple as we have thought to find the top most parent of any menu . Because sometime we don’t know the depth i.e level at which the top most parent  is.

Here we actually don’t know the depth or level of top most parent . If you don’t know the level then use the recursive function it will save your cost of programming . Recursive function will solve your problem with magic:

Here is the Code :

 function get_most_root_of_any_id($id=NULL){

            return false;

        $result = $this->CI->db->get("table_name");

            return false;

      $record =  $result->first_row();

            return $id;
        return $this->get_most_root_of_any_id($record->parent_id);


This Example is made on the basis of Codeigniter , So please modify as per your need . More on RECURSION Enjoy…