php递归无限极分类
递归无限级分类有几种形式,我这里只举例比较常用的三种:
第一种:返回有排序的数组:
<?php $data = array( 1 => array( ‘id‘ => 1, ‘pid‘ => 0, ‘user_name‘ => ‘one‘, ), 2 => array( ‘id‘ => 2, ‘pid‘ => 1, ‘user_name‘ => ‘two‘, ), 3 => array( ‘id‘ => 3, ‘pid‘ => 1, ‘user_name‘ => ‘two‘, ), 4 => array( ‘id‘ => 4, ‘pid‘ => 2, ‘user_name‘ => ‘three‘, ), 5 => array( ‘id‘ => 5, ‘pid‘ => 2, ‘user_name‘ => ‘three‘, ), 6 => array( ‘id‘ => 6, ‘pid‘ => 5, ‘user_name‘ => ‘four‘, ), ); function genCate( $data, $pid = 0, $level = 0 ) { static $result = array(); $result = ($level == 0) ? array() : $result; $prefix = ($level == 0) ? ‘‘ : str_repeat( ‘-‘, $level ); foreach ( $data as $key => $row ) { if ( $row[‘pid‘] == $pid ) { $row[‘user_name‘] = $prefix . $row[‘user_name‘]; $result[] = $row[‘user_name‘]; genCate( $data, $row[‘id‘], $level + 1 ); } } return $result; } echo ‘<pre>‘; $result = genCate( $data ); print_r( $result ); exit; ?>
第二种:返回html字符串形式:
function getTreeHtml( $data, $pId ) { $html = ‘‘; foreach ( $data as $k => $v ) { if ( $v[‘pid‘] == $pId ) { $html .= "<li>" . $v[‘user_name‘]; $html .= getTree( $data, $v[‘id‘] ); $html = $html . "</li>"; } } return $html ? ‘<ul>‘ . $html . ‘</ul>‘ : $html; }
第三种:返回多维数组形式:
function getTreeArray( $data, $pId = 0 ) { $tree = array(); foreach ( $data as $key => $value ) { if ( $value[‘pid‘] == $pId ) { $value[‘childrens‘] = getTree( $data, $value[‘id‘] ); $tree[] = $value; } } return $tree; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。