在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
需求:
需要的数据规则: 1 // demo data
2 var data = {
3 name: 'My Tree',
4 children: [
5 { name: 'hello' },
6 { name: 'wat' },
7 {
8 name: 'child folder',
9 children: [
10 {
11 name: 'child folder',
12 children: [
13 { name: 'hello' },
14 { name: 'wat' }
15 ]
16 },
17 { name: 'hello' },
18 { name: 'wat' },
19 {
20 name: 'child folder',
21 children: [
22 { name: 'hello' },
23 { name: 'wat' }
24 ]
25 }
26 ]
27 }
28 ]
29 }
mysql数据库结构: PHP代码(laravel5.4): 1 public function show($user_id)
2 {
3 $arr = array();
4
5 $data = DB::table("directory")->where('user_id', $user_id)->get();
6 if ($data->isEmpty()) {
7 return "no data!";
8 }
9 //组合数据
10 foreach ($data as $k => $v) {
11 array_push($arr, array('id' => $v->id, 'name' => $v->name, 'pid' => $v->parent_id));
12 }
13 //结果:
14 // $arr = array(
15 // array('id'=>1,'name'='视频','pid'=>0),
16 // array('id'=>2,'name'='图片','pid'=>0),
17 // array('id'=>3,'name'='科幻','pid'=>1),
18 // array('id'=>4,'name'='音乐','pid'=>0),
19 // array('id'=>5,'name'='流行','pid'=>4),
20 // array('id'=>6,'name'='变形金刚','pid'=>3),
21 // array('id'=>7,'name'='风景','pid'=>2),
22 // )
23 function get_attr($a, $pid)
24 {
25 $tree = array(); //每次都声明一个新数组用来放子元素
26 foreach ($a as $v) {
27 if ($v['pid'] == $pid) {
28 //匹配子记录
29 $v['children'] = get_attr($a, $v['id']); //递归获取子记录
30 if ($v['children'] == null) {
31 unset($v['children']); //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
32 }
33 $tree[] = $v; //将记录存入新数组
34 }
35 }
36 return $tree; //返回新数组
37 }
38 return get_attr($arr, 0);
39 }
结果: [
{
"id": 1,
"name": "视频",
"pid": 0,
"children": [
{
"id": 4,
"name": "科幻",
"pid": 1,
"children": [
{
"id": 6,
"name": "变形金刚",
"pid": 4
}
]
}
]
},
{
"id": 2,
"name": "图片",
"pid": 0,
"children": [
{
"id": 7,
"name": "风景",
"pid": 2
}
]
},
{
"id": 3,
"name": "音乐",
"pid": 0,
"children": [
{
"id": 5,
"name": "流行",
"pid": 3
}
]
}
]
|
2022-08-30
2022-08-18
2022-11-06
2022-08-14
2022-07-18
请发表评论