无限极分类处理

无限极分类处理_第1张图片

近期有个关于无限分类关系的统计处理。要求使用树型结构,无奈用了layui的表格展示,外加插件treetable和导出插件excel。
针对无限极这块从父级查询子级很长见,但是要从子级查父级一下子懵逼了。
自己反复探索了几次。

  • 上代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
 $arr = [
[
'id' => 1,
'parentId' => -1,
'name' => '广东省',
],
[
'id' => 2,
'parentId' => 1,
'name' => '深圳市',
],
[
'id' => 3,
'parentId' => 2,
'name' => '南山区',
],
[
'id' => 4,
'parentId' => 3,
'name' => '粤海街道办',
],
[
'id' => 5,
'parentId' => -1,
'name' => '江西省',
],
[
'id' => 6,
'parentId' => 5,
'name' => '吉安市',
],
[
'id' => 7,
'parentId' => 6,
'name' => '吉州区',
],
[
'id' => 8,
'parentId' => 7,
'name' => '河东街道办',
],
[
'id' => 9,
'parentId' => 3,
'name' => '西丽街道办',
],
[
'id' => 10,
'parentId' => 7,
'name' => '文山街道办',
],
[
'id' => 11,
'parentId' => 6,
'name' => '青原区',
]
];
//提取id为键
function changeData($data)
{
$lists = [];
foreach ($data as $k => $v) {
$lists[$v['id']] = $v;
}
return $lists;
}

//父级查询子级
function getParent($data)
{
$list = changeData($data);
$tree = [];
foreach ($list as $k) {
if (isset($list[$k['parentId']]) && $k['parentId'] != -1) {
$list[$k['parentId']]['items'][$k['id']] =& $list[$k['id']];
} else {
$tree[$k['id']] =& $list[$k['id']];
}
}
return $tree;
}

//子级查询父级
function getChild($data)
{
$list = changeData($data);
$tree = [];
foreach ($list as $k => $v) {
if ($v['parentId'] != -1) {
$list[$v['id']]['items'][$v['parentId']] =& $list[$v['parentId']];
} else {
$tree =& $list;
}
}
return $tree;
}

//组合子级到父级关系
function getData($gets)
{
$list = [];
$tem = '';
foreach ($gets as $k => $v) {
if ($v['parentId'] != -1) {
$temp = $v['name'];
if (count($v['items']) > 0) {
$tem = $v['items'][$v['parentId']]['name'];
if (count($v['items'][$v['parentId']]['items']) > 0) {
$tp = getData($v['items'][$v['parentId']]['items']);
}
}
if (empty($tem)) {
$tems = $v['name'];
} else {
$tems = $temp . '->' . $tem;
}
if (count($tp) > 0) {
$list[] = $tems . '->' . $tp[0];
unset($tp);
} else {
$list[] = $tems;
}
} else {
$list[] = $v['name'];
}
}
return $list;
}

$gets = getChild($arr);;
$ss = getData($gets);
print_r($ss);
exit;

你可能感兴趣的:(无限极分类处理)