脚本宝典收集整理的这篇文章主要介绍了php – 获取所有类别(多级),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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个级别的类别.
public function getCategoryTreeForParentId($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->getCategoryTreeForParentId($category['id']); $categories[$mainCategory->id] = $category; } return $categories; }
通过预加载所有类别并在阵列上操作,可以大大提高此方法,从而跳过每个新parent_id的查询.
我也没有使用codeigniter的对象,因为我不知道它们.如果它们支持魔术setter / getter或者可以说服它们获取一系列子对象,那么应该使用它们来代替我在这里构建的数组.
算法的作用是:使用给定的parent_id加载所有类别,遍历所有这些类别,将iteration-category-id假设为parent_id并为其加载所有内容.
这有效地加载所有类别,只要它们引用现有类别.
涉及到一个轻微的危险:当您构建类别A和B时,其中A将B作为父级,B将A作为父级,您将遇到无限循环,因为它们会一次又一次地相互加载.这会强制您在数据中使用干净的树结构.
更新
因为这仍然得到了回报:
有关此实施的另一个建议.
如果您的类别树更大或具有多个级别,则可能会遇到性能问题,因为此实现会使用新的查询参数一次又一次地加载类别.这很容易导致数十,数百或数千个查询,具体取决于您的类别树.
一种更有效的方法是从类别表中加载所有类别(使用一个查询),并在应用程序中使用递归对它们进行排序.这是极少数情况之一,早期评估确实可以提高性能.
以上是脚本宝典为你收集整理的php – 获取所有类别(多级)全部内容,希望文章能够帮你解决php – 获取所有类别(多级)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。