Public function getrtree(){ $data[]=array('id'=>1,'pid'=>0,'name'=>'中國'); $data[]=array('id'=>2,'pid'=>0,'name'=>'美國'); $data[]=array('id'=>3,'pid'=>0,'name'=>'韓國'); $data[]=array('id'=>4,'pid'=>1,'name'=>'北京'); $data[]=array('id'=>5,'pid'=>1,'name'=>'上海'); $data[]=array('id'=>6,'pid'=>1,'name'=>'廣西'); $data[]=array('id'=>7,'pid'=>6,'name'=>'桂林'); $data[]=array('id'=>8,'pid'=>6,'name'=>'南寧'); $data[]=array('id'=>9,'pid'=>6,'name'=>'柳州'); $data[]=array('id'=>10,'pid'=>2,'name'=>'紐約'); $data[]=array('id'=>11,'pid'=>2,'name'=>'華盛頓'); $data[]=array('id'=>12,'pid'=>3,'name'=>'首爾'); $tree=$this->build_tree($data,0); print_r($tree); print(json_encode($tree,true)); } function findChild(&$arr,$id){ $childs=array(); foreach ($arr as $k => $v){ if($v['pid']== $id){ $childs[]=$v; } } return $childs; } function build_tree($rows,$root_id){ $childs=$this->findChild($rows,$root_id); if(empty($childs)){ return null; } foreach ($childs as $k => $v){ $rescurTree=$this->build_tree($rows,$v['id']); if( null != $rescurTree){ $childs[$k]['childs']=$rescurTree; } } return $childs; }