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 '[]';
}
foreach ($childs as $k => $v){
$rescurTree=$this->build_tree($rows,$v['id']);
if( null != $rescurTree){
$childs[$k]['data']=$rescurTree;
}
$childs[$k]['value'] = $v['id'];
}
return $childs;
}
public function test(){
$sql = db('auth_rule')->select();
$data = $this->build_tree($sql,0);
return json($data) ;
}
返回的json:
[{
"id": 1,
"name": "sys",
"title": "系统设置",
"type": 1,
"status": 1,
"condition": "",
"pid": 0,
"level": 0,
"sort": 7,
"data": [{
"id": 11,
"name": "conf\/lst",
"title": "配置列表",
"type": 1,
"status": 1,
"condition": "",
"pid": 1,
"level": 1,
"sort": 50,
"data": [{
"id": 12,
"name": "conf\/add",
"title": "添加配置",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50
}, {
"id": 13,
"name": "conf\/del",
"title": "配置删除",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50
}, {
"id": 14,
"name": "conf\/edit",
"title": "配置编辑",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50
}]
}, {
"id": 9,
"name": "conf\/conf",
"title": "配置项",
"type": 1,
"status": 1,
"condition": "",
"pid": 1,
"level": 1,
"sort": 50
}]
}, {
"id": 15,
"name": "admin",
"title": "管理员",
"type": 1,
"status": 1,
"condition": "",
"pid": 0,
"level": 0,
"sort": 50,
"data": [{
"id": 16,
"name": "admin\/lst",
"title": "管理员列表",
"type": 1,
"status": 1,
"condition": "",
"pid": 15,
"level": 1,
"sort": 50,
"data": [{
"id": 17,
"name": "admin\/add",
"title": "管理员添加",
"type": 1,
"status": 1,
"condition": "",
"pid": 16,
"level": 2,
"sort": 50
}, {
"id": 18,
"name": "admin\/del",
"title": "管理员删除",
"type": 1,
"status": 1,
"condition": "",
"pid": 16,
"level": 2,
"sort": 50
}, {
"id": 19,
"name": "admin\/edit",
"title": "管理员修改",
"type": 1,
"status": 1,
"condition": "",
"pid": 16,
"level": 2,
"sort": 50
}]
}]
}]
但是用js去获取res.length的时候,却提示cannot read property 'length' of undefined