php根据路径列表生成bootstrap treeview

有这么一个需求,需要根据svn生成的版本之间差异的文件列表,生成一个treeview。

数据样本如下:

1
2
3
4
5
6
7
8
9
10
11
$defaultStr = [
'Public/images/list/order.png',
'Public/images/list/reverse.png',
'Application/Crm/View/ReturnWork/visitRecord.html',
'Application/Crm/View/ReturnWork/myVisit.html',
'Application/Crm/View/ReturnWork/memberReturn.html',
'Application/Crm/View/ReturnWork/fitReturn.html',
'Application/Crm/View/ReturnWork/emergencReturn.html',
'Application/Crm/View/UserManagement/user_list.html',
'Application/Crm/View/UserManagement/add_maternal.html',
'ver.txt'];

思路如下,先根据 / 符号拆分路径成数组,拼凑tree数组。最后根据tree数组递归生成json数组。

生成数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$tree=array();

function pushNode($subtree,$name){
if(!empty($name)){
$tmpname=end($name);
if(!array_key_exists(end($name),$subtree)){
$subtree[$tmpname]=array();
}
array_pop($name);
$subtree[$tmpname]=pushNode($subtree[$tmpname],$name);
return $subtree;
}
}

for($i=0;$i<count($defaultStr);$i++){
$path_str=array_reverse(explode('/', $defaultStr[$i]));
$tree = pushNode($tree,$path_str);
}
var_dump($tree);

生成类似如下的数组

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

array(3) {
["Public"]=>
array(1) {
["images"]=>
array(1) {
["list"]=>
array(2) {
["order.png"]=>
NULL
["reverse.png"]=>
NULL
}
}
}
["Application"]=>
array(1) {
["Crm"]=>
array(1) {
["View"]=>
array(2) {
["ReturnWork"]=>
array(5) {
["visitRecord.html"]=>
NULL
["myVisit.html"]=>
NULL
["memberReturn.html"]=>
NULL
["fitReturn.html"]=>
NULL
["emergencReturn.html"]=>
NULL
}
["UserManagement"]=>
array(2) {
["user_list.html"]=>
NULL
["add_maternal.html"]=>
NULL
}
}
}
}
["ver.txt"]=>
NULL
}

递归生成树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//递归生成树
function makeJsonTree($tree){
$json=[];
if(!empty($tree)){
foreach ($tree as $key => $value){
$jsonNode=[];
$jsonNode['text']=$key;
if($value!==null){
$jsonNode['nodes']=makeJsonTree($value);
}
array_push($json,$jsonNode);
}
}
return $json;
}

生成最终符合bootstrap treeview的格式

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
[
{
text: "Public",
nodes: [
{
text: "images",
nodes: [
{
text: "list",
nodes: [
{
text: "order.png"
},
{
text: "reverse.png"
}
]
}
]
}
]
},
{
text: "Application",
nodes: [
{
text: "Crm",
nodes: [
{
text: "View",
nodes: [
{
text: "ReturnWork",
nodes: [
{
text: "visitRecord.html"
},
{
text: "myVisit.html"
},
{
text: "memberReturn.html"
},
{
text: "fitReturn.html"
},
{
text: "emergencReturn.html"
}
]
},
{
text: "UserManagement",
nodes: [
{
text: "user_list.html"
},
{
text: "add_maternal.html"
}
]
}
]
}
]
}
]
},
{
text: "ver.txt"
}
]

关注公众号 尹安灿