Welcome Guest, Not a member yet? Register   Sign In
Forum Categories
#1

[eluser]coxdabd[/eluser]
Hi all, I'm coding up a custom forum for a client, looking very good. Hit a bit of a wall on how I should fetch the categories and subcategories.

I'm ok getting the categories in a model, but then I also need to fetch the subcategories of that category - I was going to use a foreach loop in the view. Any ideas on how this can be achieved would be appreciated as I can't continue without a little help Smile
#2

[eluser]coxdabd[/eluser]
Anyone got any ideas?
#3

[eluser]meigwilym[/eluser]
Show your code.
#4

[eluser]coxdabd[/eluser]
I don't have any (yet). I just need a bit of steer of a way to do this in a MVC pattern. I would normally put a loop within a loop.
#5

[eluser]PhilTem[/eluser]
Either, you do it with adjacency list or with nested sets. The queries for nested sets can be found when you google for 'joe celko nested set'. For adjacency lists it's easier.

Code:
function get_categories($parent_id = '0')
{
  $this->db
          ->select('*')
          ->from('your_categories_table')
          ->order_by('category_name') // or whatever else ordering you desire
          ->where('parent_id', $parent_id);
  
  $query = $this->db->get();
  
  $categories = array();
  
  foreach ( $query->result() as $row )
  {
    // We'll make use of a temporary variable
    $tmp = $row;
    
    // Grab the children with recursive function-call
    $tmp['children'] = $this->get_categories($row->parent_id);
    
    // Assign it to the return
    $categories[] = $tmp;
  }
  
  return $categories;
}

Assuming you have a table with a column parent_id which defaults to 0 for categories and holds the ID of the parent-category for each sub-category.

If you don't mind learning nested sets, then have a look at them Wink But it's a lot of stuff to understand and the queries are way more difficult than for adjacency lists - though they run much faster Wink




Theme © iAndrew 2016 - Forum software by © MyBB