Welcome Guest, Not a member yet? Register   Sign In
Recursive funciton in Codeigniter
#1

[eluser]foysal[/eluser]
I have table named 'users', where columns are like user_id, parent_user_id etc. That means every user has a parent user. I would like to view user like below

user1(parent user of user2)
-user2(parent user of user3)
--user3(parent user of user4)
---user4
user5(parent user of user)
-user6

I am trying to do this using the following function of a model with recursive function.

Code:
public function user_list($user_id)
{
  $user_array = array();
  $query = $this->db->get_where('users',array('user_parent_user_id'=>$user_id,'user_type'=>3,'user_status'=>1));
  $results  = $query->result();
  if(empty($results))
  {
   return $results;
  }
  else
  {
   $user_array[] = $results[0]->user_id;
   $this->user_list($results[0]->user_id);
  }
  
  return $user_array;
}

Could any one help me in this regard ??

Thanks

Foysal
#2

[eluser]WanWizard[/eluser]
You're trying to implement an adjecency list. Google that and you get tons of solutions.
#3

[eluser]foysal[/eluser]
I searched a lot in Google "adjacency list using codeigniter" but could not get any solution .

I am trying now with following function of model.

Code:
public function user_list($user_id)
{
  $query_parent_user = $this->db->get_where('users',array('user_parent_user_id'=>$user_id,'user_type'=>3,'user_status'=>1));
  $results_parent_user  = $query_parent_user->result();
  $user_array[] = $results_parent_user[0]->user_id;
  if(empty($results_parent_user))
  {
   return $user_array;
  }
  else
  {
   foreach($results_parent_user as $result_parent_user)
   {
    $query_child_user = $this->db->get_where('users',array('user_parent_user_id'=>$result->user_parent_user_id,'user_type'=>3,'user_status'=>1));
    $results_child_user  = $query_child_user->result();
    $user_array[] = $results_child_user[0]->user_id;
    $this->user_list($results_child_user[0]->user_parent_user_id);
   }
  }
  
}
#4

[eluser]yacman[/eluser]
Here you go!

Code:
function userTree($parent_id=0) {
     $query = $this->db->get_where('users',array('user_parent_user_id'=>$parent_id,'user_type'=>3,'user_status'=>1));

     $branch = array();
     if (!empty($query) && $query->num_rows() > 0) {
        $branch = $query->result();
        foreach ($branch as $key=>$child) {
                   $branch[$key]->children = userTree($child->user_id);
        }  
        unset($key);
        unset($child);
     }

    return $branch;
}

$user_tree = userTree();

print_r($user_tree);




Theme © iAndrew 2016 - Forum software by © MyBB