PHP 递归查询数据库 # 需求 如下图数据结构 ~~~ id name parent-id 1 菜单 0 2 菜单 1 3 菜单 2 4 菜单 3 ~~~ 常规的菜单形成树结构的普遍做法是 将所有数据一次性检索得出,然后使用递归检索进行排序成data['children']的形式 **但某些特定的需求下,需要检索某个值所有的子菜单集合** # 正解 如您的数据库是oracle,则可以使用start with xx CONNECT BY PRIOR ID = PID进行递归搜索,使用方法建议百度。 如您使用的是MYSQL,网上有函数可以实现。 如您希望使用框架语言解决。 则可使用下面方式 ~~~ select id from ( select t1.id, if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild from ( select id,parent_id from table_name t where t.delete_time is null order by parent_id, id ) t1, (select @pids := 您的ID) t2 ) t3 where ischild != 0; ~~~ sql返回所有的子节点ID集合  如带入1,则结果集会返回id 2,3,4,(注意,不返回ID自身) 如您想获取具体的数据,可自行查询。