CodeIgniter 3递归查询分类ID:修正获取全部分类ID问题
如何获取CodeIgniter 3中分类表的所有层级ID数组?
分类表结构
categories id| name |parent 1 | shoes |0 2 | women_shoes |1 3 | man_shoes |1 4 | sweets |0 5 | man_sweets |4 6 | women_sweets |4 7 | women_red_sweets |6 8 | women_green_sweets |6 9 | men_blue_sweets |5
需求
使用CodeIgniter 3编写助手函数,获取包含所有分类ID的一维数组,期望结果为 array(1,2,3,4,5,6,7,8,9)(注:原需求提及array(1,2,3,4,5,6,7,8),但表中存在ID9,推测为笔误)。
原代码问题
以下是原助手文件中的PHP代码:
function categories_list($id = 0, &$list = array()) { /// parent_id $ci = & get_instance(); $cat = $ci->db->select("*") ->from("categories") ->where("parent",$id) ->get()->result(); foreach ($cat as $value) { array_push($list,$value->id); categories_list($list->id,$list); // 此处参数错误 } return ($list); } $liste = categories_list(0); print_r($liste);
当前代码仅输出 array(1,4),无法遍历子分类,核心错误是递归调用时传错了参数:$list->id 是错误写法($list是数组,不存在id属性),应该传入当前分类的ID即$value->id。另外函数参数中&$list = array()的写法在PHP中属于不规范的引用默认参数,虽然能运行但建议调整写法避免潜在问题。
修正后的代码
function categories_list($parentId = 0) { $ci = &get_instance(); static $categoryIds = array(); // 获取当前父分类下的所有子分类 $categories = $ci->db->select('id') ->from('categories') ->where('parent', $parentId) ->get()->result(); foreach ($categories as $category) { // 添加当前分类ID到数组 $categoryIds[] = $category->id; // 递归遍历当前分类的子分类 categories_list($category->id); } return $categoryIds; } // 使用示例 $liste = categories_list(0); print_r($liste);
代码说明
- 使用
static变量$categoryIds,确保递归过程中数组不会被重新初始化,持续收集所有分类ID; - 递归调用时传入当前分类的
$category->id,正确遍历子分类层级; - 仅查询
id字段,减少数据库查询的数据量,提升性能; - 避免了引用参数可能带来的潜在问题,代码更简洁易维护。
执行后将输出预期的完整分类ID数组:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 9 [6] => 6 [7] => 7 [8] => 8 )(顺序由数据库查询结果决定,若需要特定顺序可添加order_by)。
内容的提问来源于stack exchange,提问作者haloman
相关产品推荐
相关产品推荐

