我正在使用 codeigniter 并有一个包含 3 列(id、name、parent_id)的表。一个类别可以有很多子类别,一个子类别可以有很多子子类别。
我一直在尝试使用以下代码获取所有类别及其子类别:
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;
    }
但它只返回 1 级类别。
我的问题是如何完成我的任务:获取每个级别的所有类别和子类别。