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
|
/** * 创建父节点树形数组 * 参数 * $ar 数组,邻接列表方式组织的数据 * $id 数组中作为主键的下标或关联键名 * $pid 数组中作为父键的下标或关联键名 * 返回 多维数组 **/ function find_parent( $ar , $id = 'id' , $pid = 'pid' ) { foreach ( $ar as $v ) $t [ $v [ $id ]] = $v ; foreach ( $t as $k => $item ){ if ( $item [ $pid ] ){ if ( ! isset( $t [ $item [ $pid ]][ 'parent' ][ $item [ $pid ]]) ) $t [ $item [ $id ]][ 'parent' ][ $item [ $pid ]] =& $t [ $item [ $pid ]]; } } return $t ; } /** * 创建子节点树形数组 * 参数 * $ar 数组,邻接列表方式组织的数据 * $id 数组中作为主键的下标或关联键名 * $pid 数组中作为父键的下标或关联键名 * 返回 多维数组 **/ function find_child( $ar , $id = 'id' , $pid = 'pid' ) { foreach ( $ar as $v ) $t [ $v [ $id ]] = $v ; foreach ( $t as $k => $item ){ if ( $item [ $pid ] ) { $t [ $item [ $pid ]][ 'child' ][ $item [ $id ]] =& $t [ $k ]; } } return $t ; } $data = array ( array ( 'ID' =>1, 'PARENT' =>0, 'NAME' => '祖父' ), array ( 'ID' =>2, 'PARENT' =>1, 'NAME' => '父亲' ), array ( 'ID' =>3, 'PARENT' =>1, 'NAME' => '叔伯' ), array ( 'ID' =>4, 'PARENT' =>2, 'NAME' => '自己' ), array ( 'ID' =>5, 'PARENT' =>4, 'NAME' => '儿子' ), ); $p = find_parent( $data , 'ID' , 'PARENT' ); $c = find_child( $data , 'ID' , 'PARENT' ); Print_r ( $c ); |
执行效果:
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
|
Array ( [1] => Array ( [ID] => 1 [PARENT] => 0 [NAME] => 祖父 [child] => Array ( [2] => Array ( [ID] => 2 [PARENT] => 1 [NAME] => 父亲 [child] => Array ( [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 儿子 ) ) ) ) ) [3] => Array ( [ID] => 3 [PARENT] => 1 [NAME] => 叔伯 ) ) ) [2] => Array ( [ID] => 2 [PARENT] => 1 [NAME] => 父亲 [child] => Array ( [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 儿子 ) ) ) ) ) [3] => Array ( [ID] => 3 [PARENT] => 1 [NAME] => 叔伯 ) [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 儿子 ) ) ) [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 儿子 ) ) |
以上这篇PHP树-不需要递归的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。