栏目数组:
1
2
3
4
5
6
7
8
|
$arr =Array( Array( 'cid' => 2, 'cname' => '新闻' , 'pid' => 0), Array( 'cid' => 4, 'cname' => '体育' , 'pid' => 0), Array( 'cid' => 5, 'cname' => '娱乐' , 'pid' => 0), Array( 'cid' => 7, 'cname' => '热点新闻' , 'pid' =>2), Array( 'cid' => 8, 'cname' => '小众新闻' , 'pid' => 2), Array( 'cid' => 9, 'cname' => '民谣新闻' , 'pid' => 8), ); |
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
|
<?php $arr =Array( Array( 'cid' => 2, 'cname' => '新闻' , 'pid' => 0), Array( 'cid' => 4, 'cname' => '体育' , 'pid' => 0), Array( 'cid' => 5, 'cname' => '娱乐' , 'pid' => 0), Array( 'cid' => 7, 'cname' => '热点新闻' , 'pid' =>2), Array( 'cid' => 8, 'cname' => '小众新闻' , 'pid' => 2), Array( 'cid' => 9, 'cname' => '民谣新闻' , 'pid' => 8), ); function formatTree( $array , $pid = 0, $level = 1, $field = array ( 'pid' => 'pid' , 'id' => 'id' , 'children' => 'children' )){ $arr = array (); foreach ( $array as & $v ) { if ( $v [ $field [ 'pid' ]] == $pid ) { $v [ 'level' ] = $level ; $tem = formatTree( $array , $v [ $field [ 'id' ]], $v [ 'level' ]+1, $field ); //判断是否存在子数组 $tem && $v [ $field [ 'children' ]] = $tem ; $arr [] = $v ; } } return $arr ; } $tree = formatTree( $arr ,0,1, $field = array ( 'pid' => 'pid' , 'id' => 'cid' , 'children' => 'children' ) ); echo '<pre>' ; print_r( $tree ); ?> |
我们有两个方法来进行软件设计:一个是让其足够的简单以至于让BUG无法藏身;另一个就是让其足够的复杂,让人找不到BUG。前者更难一些。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!