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
3 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
cannot read property 'length' of undefined
的意思是undefined
沒有length
屬性,說明說你的res
是undefined
,undefined
當然沒有length
屬性了。
為啥res
會是undefined
?不是在控制臺里打印出來了嗎?有兩種可能,第一種是你打印的根本就不是同一個res.length
(作用域的問題),第二種,也是我認為非常有可能的,就是你還沒搞懂js的異步,前端在發請求的時候需要你提供一個“回調函數”,只有在這個回調函數里你才能獲得res
。比如
let res;
$.get(url, data => res = data);
console.log(res); // undefined
res.length // cannot read property 'length' of undefined
$.get(url, data => {
console.log(data);
console.log(data.length);
// do something here
});
- 3 回答
- 0 關注
- 666 瀏覽
添加回答
舉報
0/150
提交
取消