1 /**
2 * User: finn.lee
3 * Date: 2016/3/5 14:25
4 */
5 $rows = array(
6 0=>array(
7 'cat_id' => 1,
8 'name' => 'dev',
9 'pid' => 0
10 ),
11 1=>array(
12 'cat_id' => 2,
13 'name' => 'php',
14 'pid' => 1
15 ),
16 2=>array(
17 'cat_id' => 3,
18 'name' => 'smarty',
19 'pid' => 2
20 ),
21 3=>array(
22 'cat_id' => 4,
23 'name' => 'life',
24 'pid' => 0
25 ),
26 4=>array(
27 'cat_id' => 5,
28 'name' => 'pdo',
29 'pid' => 2
30 ),
31 5=>array(
32 'cat_id' => 6,
33 'name' => 'pdo-mysql',
34 'pid' => 5
35 ),
36 6=>array(
37 'cat_id' => 7,
38 'name' => 'java',
39 'pid' => 1
40 )
41 );
42
43 // 72648
44 // 84072
45
46 function findChild(&$arr,$id){
47
48 $childs=array();
49 foreach ($arr as $k => $v){
50 if($v['pid']== $id){
51 $childs[]=$v;
52 }
53 }
54 return $childs;
55 }
56 function build_tree($root_id){
57 global $rows;
58 $childs=findChild($rows,$root_id);
59 if(empty($childs)){
60 return null;
61 }
62 foreach ($childs as $k => $v){
63 $rescurTree=build_tree($v['cat_id']);
64 if( null != $rescurTree){
65 $childs[$k]['childs']=$rescurTree;
66 }
67 }
68 return $childs;
69 }
70
71
72 $tree=build_tree(0);
73
74 echo memory_get_usage();
75
76 print_r($tree);
注: $rows是活的 , $root_id是活的
来源:http://www.cnblogs.com/finnlee/p/5244932.html