Fastadmin生成树型结构
fastadmin
自带 Tree
类生成树型结构,该类所在位置extend/fast/Tree.php
# 获取实例
$tree = Tree::instance();
1
# 初始化
$data = [
['id' => 1, 'pid' => 0, 'name' => '一级分类'],
['id' => 2, 'pid' => 1, 'name' => '二级分类'],
['id' => 3, 'pid' => 2, 'name' => '三级分类'],
];
/**
* 初始化方法
* @param array $arr 2维数组,例如:
* array(
* 1 => array('id'=>'1','pid'=>0,'name'=>'一级栏目一'),
* 2 => array('id'=>'2','pid'=>0,'name'=>'一级栏目二'),
* 3 => array('id'=>'3','pid'=>1,'name'=>'二级栏目一'),
* 4 => array('id'=>'4','pid'=>1,'name'=>'二级栏目二'),
* 5 => array('id'=>'5','pid'=>2,'name'=>'二级栏目三'),
* 6 => array('id'=>'6','pid'=>3,'name'=>'三级栏目一'),
* 7 => array('id'=>'7','pid'=>3,'name'=>'三级栏目二')
* )
* @param string $pidname 父字段名称
* @param string $nbsp 空格占位符
* @return Tree
*/
$tree->init($data, 'pid', '#');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 获取树状数组
/**
*
* 获取树状数组
* @param string $myid 要查询的ID
* @param string $itemprefix 前缀
* @return array
*/
$treeArr = $tree->getTreeArray(0, '$');
// 结果返回, 如果前缀和占位符都不穿,spacer为空字符串
/*
array(1) {
[0] => array(5) {
["id"] => int(1)
["pid"] => int(0)
["name"] => string(12) "一级分类"
["spacer"] => string(4) "$└"
["childlist"] => array(1) {
[0] => array(5) {
["id"] => int(2)
["pid"] => int(1)
["name"] => string(12) "二级分类"
["spacer"] => string(6) "$##└"
["childlist"] => array(1) {
[0] => array(5) {
["id"] => int(3)
["pid"] => int(2)
["name"] => string(12) "三级分类"
["spacer"] => string(8) "$####└"
["childlist"] => array(0) {
}
}
}
}
}
}
}
*/
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
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
# 将getTreeArray
的结果返回为二维数组
/**
* 将getTreeArray的结果返回为二维数组
* @param array $data
* @param string $field
* @return array
*/
$list = $tree->getTreeList($treeArr, 'name')
// 返回结果
/*
array(3) {
[0] => array(5) {
["id"] => int(1)
["pid"] => int(0)
["name"] => string(17) "$└ 一级分类"
["spacer"] => string(4) "$└"
["haschild"] => int(1)
}
[1] => array(5) {
["id"] => int(2)
["pid"] => int(1)
["name"] => string(19) "$##└ 二级分类"
["spacer"] => string(6) "$##└"
["haschild"] => int(1)
}
[2] => array(5) {
["id"] => int(3)
["pid"] => int(2)
["name"] => string(21) "$####└ 三级分类"
["spacer"] => string(8) "$####└"
["haschild"] => int(0)
}
}
*/
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
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
上次更新: 2023/09/22, 16:54:32