问答 / 7 / 3 / 创建于 2年前
假设有一树形数据表,id,name,pid
现在给定了一组ID:[5,8,9]
想查询出5、8、9的完整树形结构怎么实现最好?
使用扩展包, 013. 嵌套集合模型(无限极分类)——kalnoy/nestedset(代替 baum/baum)
万变不离递归
先把所有id 查出来 用php在做递归.还有这种需求,我个人是觉得完全没必要在去引一个什么包.
/** * 递归生成树 * * @param $items array * @param $pid int * @param $children bool * @param $title string * * @return array */ function getTree($items , int $pid = 0, bool $children = true, string $title = 'children'): array { // 每次都声明一个新数组用来放子元素 $tree = []; foreach( $items as $item ){ // 匹配子记录 if( $item['pid'] == $pid){ // 递归获取子记录 $item[$title] = getTree( $items , $item['id'], $children, $title); if( $item[$title] == null && $children){ // 如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选) unset($item[$title]); } // 将记录存入新数组 $tree[] = $item; } } // 返回新数组 return $tree; }
我要举报该,理由是:
使用扩展包, 013. 嵌套集合模型(无限极分类)——kalnoy/nestedset(代替 baum/baum)
万变不离递归
先把所有id 查出来 用php在做递归.
还有这种需求,我个人是觉得完全没必要在去引一个什么包.