PHP无限极分类巧用引用生成树
首先看代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
function generateTree($items){ $tree = array(); foreach($items as $item){ if (isset($items[$item[ 'pid' ]])){ $items[$item[ 'pid' ]][ 'son' ][] = &$items[$item[ 'id' ]]; } else { $tree[] = &$items[$item[ 'id' ]]; } } return $tree; } $items = 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' => 3 , 'name' => '长丰县' ), 5 => array( 'id' => 5 , 'pid' => 1 , 'name' => '安庆市' ), ); print_r(generateTree($items)); |
输出结果
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
|
Array ( [ 0 ] => Array ( [id] => 1 [pid] => 0 [name] => 安徽省 [son] => Array ( [ 0 ] => Array ( [id] => 3 [pid] => 1 [name] => 合肥市 [son] => Array ( [ 0 ] => Array ( [id] => 4 [pid] => 3 [name] => 长丰县 ) ) ) [ 1 ] => Array ( [id] => 5 [pid] => 1 [name] => 安庆市 ) ) ) [ 1 ] => Array ( [id] => 2 [pid] => 0 [name] => 浙江省 ) ) |
果然是厉害,代码简洁精炼,无需递归,执行速度快。这是长春九龙男科上看到的,觉得很实用就收藏下来,分享给大家。