Home  >  Q&A  >  body text

ThinkPHP unlimited categories

How to perform unlimited classification based on id and pid

高洛峰高洛峰2715 days ago646

reply all(3)I'll reply

  • 迷茫

    迷茫2017-06-05 11:10:01

    Use a recursive function, but the space complexity of this method was not optimized. I forgot the previous way of writing it

    private function getTreeList($data, $pid = 0)
        {
            $resultarr = array();
            foreach ($data as $teamdata) {
                if ($teamdata['pid'] == $pid) {
                    $team_data = $teamdata;
                    $children_data = $this->getTreeList($data, $teamdata['id']);
                    $team_data['children'] = $children_data;
                    $resultarr[] = $team_data;
                }
            }
            return $resultarr;
        }

    reply
    0
  • ringa_lee

    ringa_lee2017-06-05 11:10:01

    Use recursion to loop out an array

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-05 11:10:01

    public function gettree($items, $parent_id = 'parent_id', $id = 'id'){
        $tree = array(); //格式化好的树
        if(empty($items)){
            return $tree;
        }
        foreach ($items as $item){
            if (isset($items[$item[$parent_id]])){
                $items[$item[$parent_id]]['son'][] = &$items[$item[$id]];
            }else{
                $tree[] = &$items[$item[$id]];
            }
        }
        return $tree;
    
    }

    reply
    0
  • Cancelreply