I'm using codeigniter and have a table with 3 columns (id, name, parent_id). A category can have many subcategories and a subcategory can have many sub-sub categories.
I've been trying to get all categories and their subcategories using this code:
public function getCategory($id)
{
$categories = array();
while($id != 0)
{
$this->db->from('categories'); //$this->table is a field with the table of categoris
$this->db->where('id', $id);
$this->db->limit(1);
$result = $this->db->get()->row(); //fetching the result
$categories[] = $result;
$id = $result->parent_id;
}
return $categories;
}
public function getAllCategories()
{
$this->db->select('id');
$this->db->from('categories'); //$this->table is a field with the table of categoris
$this->db->where('parent_id', 0);
$mainCategories = $this->db->get()->result(); //fetching the result
$result = array();
foreach($mainCategories as $id)
{
$result[] = $this->getCategory($id->id);
}
return $result;
}
But it returns me only 1 level categories.
My question is how to accomplish my task: get all categories and subcategories for every level.