user1987095
user1987095

Reputation: 459

display a tree of category, subcategory by given category id

Though i'm using codeigniter but it does not matter if someone can help me in simple recursive function. i have a table called 'tbl_member' where there is 3 field member_id,parent_id,name I want a tree structure for particular member id.

Ex if i send a member_id(10) it will show all children(sub_member) of that member

Upvotes: 0

Views: 1073

Answers (3)

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

Does it help??

 function get_tree($member_id){
  $result=$this->db->get_where('table',array('member_id'=>$member_id));
  $data=$result->row_array();
    $n=$this->get_child($data['member_id']);
      foreach($n as $l){
        $data[]=$l;
       }
    print_r($data);
}


function get_child($parent_id){
$result=$this->db->get_where('table',array('parent_id'=>$parent_id));
$row = $result->result_array();
foreach ($row as $key => $m) {
  if (is_array($m) && count($m) != NULL) {
      $me=$this->get_child($m['member_id']);
      foreach($me as $res){
            $row[$key][]=$res;
       }
    }
 }
  return $row;
}

Upvotes: 1

jmadsen
jmadsen

Reputation: 3675

These solutions require many, many database hits. Consider a hierarchy table structure instead:

http://codebyjeff.com/blog/2012/10/nested-data-with-mahana-hierarchy-library

Upvotes: 0

Ebrahim El Sawy
Ebrahim El Sawy

Reputation: 11

function getMemberTree($id) {
$q =  $this->db->get_where('tbl_member', array('parent_id' => $id));
if($q->num_rows() > 0) {
    foreach($q->result() as $row) {
        $first_level[] = $row;
    }
    foreach($first_level as $r) {
        $member_id = $r->member_id;
        $m = $this->db->get_where('tbl_member', array('parent_id' => $member_id));
        if($m->num_rows() > 0) {
            foreach($m->result() as $mrow) {
                $second_level[] = $mrow;
            }
        }
    }
    $data[] = $first_level;
    $data[] = $second_level;

    return $data; 

}

Upvotes: 0

Related Questions