我在弄一个项目,需要多个父id去查询其下面子id的记录,写了个函数,只能查询单个父id下面的,多个不知道怎么写了,没有思路,哪位帮下忙,在这谢过!奉上我自己写的函数:
function get_child_id($data, $parent_id = '0') { static $child; foreach ($data as $value) { if ($value['parent_id'] == $parent_id) { $child .= ',' . $value['cat_id']; $this->get_child_id($data, $value['cat_id'], $level + 1); } } return $child; }
循环调用你这个方法就可以了。
$parent_ids = array(1,2,3,4);$resul t= array();foreach($parent_ids as $parent_id){ $result[] = get_child_id($data, $parent_id);}function get_child_id($data, $parent_id = '0') { static $child; foreach ($data as $value) { if ($value['parent_id'] == $parent_id) { $child .= ',' . $value['cat_id']; $this->get_child_id($data, $value['cat_id'], $level + 1); } } return $child; } 对每个 父ID 都调用一下 get_child_id 不就行了?
不过 static $child; 会在多次调用时出问题的
多次循环 get_child_id会出现子栏目ID重复出现的情况
#2 我已经告诉你会出问题了
症结在 static $child; !
function get_child_id($data, $parent_id = '0') { $child = ''; foreach ($data as $value) { if ($value['parent_id'] == $parent_id) { $child .= ',' . $value['cat_id']; $child .= $this->get_child_id($data, $value['cat_id'], $level + 1); } } return $child; }这个我发现了,但是还是会出现子栏目ID重复的情况
贴出你的测试数据,应该是 id 不唯一(没有死循环已经对你很客气了)
贴出你的测试数据,应该是 id 不唯一(没有死循环已经对你很客气了)
我 #4 不是给你代码了吗?
我 #4 不是给你代码了吗?
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号