【发布时间】:2013-03-25 04:30:24
【问题描述】:
我正在使用 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 级类别。
我的问题是如何完成我的任务:获取每个级别的所有类别和子类别。
【问题讨论】:
-
不要忘记将您的 codeigniter 答案标记为 php,您将获得更多帮助 ;)
-
这里没有递归。
-
Offtop:你尝试过使用其他结构吗?嵌套集,可能是?使用这种结构,您必须使用递归。
-
您好,请查看此链接,这是您问题的完美解决方案....phpsollutions.blogspot.com/2014/04/…
标签: php arrays codeigniter recursion