一个遍历算法

class ProductDirModel extends Model {
    
    public function getProductDir($dirId){
        // $dirId = 591
        
    }
    
    public function f($dirId){

        $val=$this->test($dirId);
        $data['children']=$val;
        return $val;
        
        /* $productDirs = $this->f2($dirId);
        foreach ($productDirs as $productDir){
            $tempArray['children'] = array('id'=>$productDir['dir_id'],'text'=>$productDir['dir_name']);
            f($productDir[dir_id]);
        }
        return $tempArray; */
    }
    
    public function test($dirId){
        $productDirs = $this->f2($dirId);
        
        $val=array();
        foreach($productDirs as $k){
            $v = array();
            $v['id'] = $k['dir_id'];
            $v['text'] = $k['dir_name'];
            $v['expanded'] = true;
            $tempArray = $this->test($k['dir_id']);
            if(count($tempArray) != 0){
                $v['children'] = $tempArray;
                $v['leaf'] = false;
            }else{
                $v['leaf'] = true;
            }
            $val[] = $v;
             
        }
        return $val;
    }
    
    public function f2($dirId){
        $map = array();
        $map['dir_parent_id'] = $dirId;
        $returnInfo = $this->field('dir_id,dir_name')->where($map)->select();
        return $returnInfo;
    }
}   
原文地址:https://www.cnblogs.com/shaoshao/p/4386444.html