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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.