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) ;
}
returned 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
}]
}]
}]
but when you use js to get res.length, it prompts cannot read property "length" of undefined