Codeigniter Recusrsive Category List

Conside categories table with structure is id, name, parent_id.  A category can have many subcategories and a subcategory can have many sub-sub categories.

This is the code to get all categories and their subcategories.


$tree = $this->get_category_by_parent(0);

public function get_category_by_parent($parent_id = 0) {
		  $categories = array();
		  $this->db->from('categories');
		  $this->db->where('parent_id', $parent_id);
		  $result = $this->db->get()->result();
		  foreach ($result as $mainCategory) {
		    $category = array();
		    $category['id'] = $mainCategory->id;
		    $category['name'] = $mainCategory->name;
		    $category['parent_id'] = $mainCategory->parent_id;
		    $category['sub_categories'] = $this->get_category_by_parent($category['id']);
		    $categories[$mainCategory->id] = $category;
		  }
		  return $categories;
}

Category-subcategory Dropdownlist,
category_model.php:


public function fetchCategoryTree($parent_id = 0, $spacing = '', $user_tree_array = '') {
 
      if (!is_array($user_tree_array))
        $user_tree_array = array();

      $this->db->where('parent_id', $parent_id);
      $query = $this->db->get('categories');
      $result = $query->result();
      foreach ($result as $mainCategory) {
        $user_tree_array[] = array("id" => $mainCategory->id, "name" => $spacing . $mainCategory->name);
          $user_tree_array = $this->fetchCategoryTree($mainCategory->id, $spacing . '  ', $user_tree_array);
      }
      return $user_tree_array;
    }

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$categoryList = $this->category_model->fetchCategoryTree();
?>
<select>
<?php foreach($categoryList as $cl) { ?>
<option value=”<?php echo $cl[“id”] ?>”><?php echo $cl[“name”]; ?></option>
<?php } ?>
</select>

Category-SubCategory Listing,
category_model.php:

function fetchCategoryTreeList($parent_id = 0, $user_tree_array = ”) {
if (!is_array($user_tree_array))
$user_tree_array = array();

$this->db->where(‘parent_id’, $parent_id);
$query = $this->db->get(‘categories’);
$result = $query->result();
$user_tree_array[] = “<ul>”;
foreach ($result as $mainCategory) {
$user_tree_array[] = “<li>”. $mainCategory->name.”</li>”;
$user_tree_array = $this->fetchCategoryTreeList($mainCategory->id, $user_tree_array);
}
$user_tree_array[] = “</ul>”;

return $user_tree_array;
}

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$res = $this->category_model->fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}

?>

Advertisements