PHP递归遍历多维数组实现无限分类的方法。分享给大家供大家参考,具体如下:
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
|
<?php //$data[]=array('id'=>1,'parentid'=>0,'name'=>'中国','img'=>'52091199'); $data []= array ( 'id' =>1, 'parentid' =>0, 'name' => '中国' ); $data []= array ( 'id' =>2, 'parentid' =>0, 'name' => '美国' ); $data []= array ( 'id' =>3, 'parentid' =>0, 'name' => '韩国' ); $data []= array ( 'id' =>4, 'parentid' =>1, 'name' => '北京' ); $data []= array ( 'id' =>5, 'parentid' =>1, 'name' => '上海' ); $data []= array ( 'id' =>6, 'parentid' =>1, 'name' => '广西' ); $data []= array ( 'id' =>7, 'parentid' =>6, 'name' => '桂林' ); $data []= array ( 'id' =>8, 'parentid' =>6, 'name' => '南宁' ); $data []= array ( 'id' =>9, 'parentid' =>6, 'name' => '柳州' ); $data []= array ( 'id' =>10, 'parentid' =>2, 'name' => '纽约' ); $data []= array ( 'id' =>11, 'parentid' =>2, 'name' => '华盛顿' ); $data []= array ( 'id' =>12, 'parentid' =>3, 'name' => '首尔' ); $tree =build_tree( $data ,0); //echo memory_get_usage(); print_r( $tree ); $childs = array (); foreach ( $arr as $k => $v ){ if ( $v [ 'parentid' ]== $id ){ $childs []= $v ; } } return $childs ; } function build_tree( $rows , $root_id ){ $childs =findChild( $rows , $root_id ); if ( empty ( $childs )){ return null; } foreach ( $childs as $k => $v ){ $rescurTree =build_tree( $rows , $v [ 'id' ]); if ( null != $rescurTree ){ $childs [ $k ][ 'childs' ]= $rescurTree ; } } return $childs ; } ?> |
运行结果:
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
|
Array ( [0] => Array ( [id] => 1 [parentid] => 0 [name] => 中国 [childs] => Array ( [0] => Array ( [id] => 4 [parentid] => 1 [name] => 北京 ) [1] => Array ( [id] => 5 [parentid] => 1 [name] => 上海 ) [2] => Array ( [id] => 6 [parentid] => 1 [name] => 广西 [childs] => Array ( [0] => Array ( [id] => 7 [parentid] => 6 [name] => 桂林 ) [1] => Array ( [id] => 8 [parentid] => 6 [name] => 南宁 ) [2] => Array ( [id] => 9 [parentid] => 6 [name] => 柳州 ) ) ) ) ) [1] => Array ( [id] => 2 [parentid] => 0 [name] => 美国 [childs] => Array ( [0] => Array ( [id] => 10 [parentid] => 2 [name] => 纽约 ) [1] => Array ( [id] => 11 [parentid] => 2 [name] => 华盛顿 ) ) ) [2] => Array ( [id] => 3 [parentid] => 0 [name] => 韩国 [childs] => Array ( [0] => Array ( [id] => 12 [parentid] => 3 [name] => 首尔 ) ) ) ) |
© 版权声明
本文刊载的所有内容,包括文字、图片、音频、视频、软件、程序、以及网页版式设计等部门来源于互联网,版权均归原作者所有!本网站提供的内容服务于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本网站及相关权利人的合法权利。
联系信息:邮箱aoxolcom@163.com或见网站底部。
联系信息:邮箱aoxolcom@163.com或见网站底部。
THE END
请登录后发表评论
注册
社交帐号登录