Jump to content

Getting hierarchal records


tibberous

Recommended Posts

This is a simple task, but my brain apparently no longer works.

 

I have a nested category structure - each record can have a parent, that is the id of another category.

 

So:

 

id name parent

1 Sporting Goods 0

2 Golf Clubs 1

3 Baseballs 1

4 Shirts 0

 

All I want to do is write a function that takes an id and gets all the children below it. It should be like 2 functions, with one being recursive... like 10 lines total...

 

  function has_subcategories($catid){
      $result = $this->db->query("select * from `categories` where `Owner`=$catid and `active`=1 and `deleted`=0");
      
      return $result->num_rows() ? true : false;
  }
 
    function get_subcategories($catid){
        $result = $this->db->query("select * from `categories` where `Owner`='$catid' and `active`=1 and `deleted`=0");
        $children = array();
        
        foreach($result->result_array() as $subcat){
            
            //echo $subcat['id'].'-'.$this->has_subcategories($subcat['id'])."<br>";
                        
            if($this->has_subcategories($subcat['id'])){
                $children = array_merge($children, $this->get_subcategories($subcat['id']));
            } else {
                $children[] = $subcat['id'];
            }
        }
        
        return $children;
    }

 

Anyone see what I'm doing wrong? I've wrote this exact function before, not sure how I'm screwing it up.

Link to comment
https://forums.phpfreaks.com/topic/288197-getting-hierarchal-records/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.