php递归无限极分类
2020-12-13 02:38
标签:递归 php 分类 无限 递归无限级分类有几种形式,我这里只举例比较常用的三种: 第一种:返回有排序的数组: 第二种:返回html字符串形式: 第三种:返回多维数组形式:
php递归无限极分类,搜素材,soscw.com php递归无限极分类 标签:递归 php 分类 无限 原文地址:http://blog.csdn.net/zyb_icanplay7/article/details/25387743 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 ‘
‘;
$result = genCate( $data );
print_r( $result );
exit;
?>
function getTreeHtml( $data, $pId ) {
$html = ‘‘;
foreach ( $data as $k => $v ) {
if ( $v[‘pid‘] == $pId ) {
$html .= "
‘ . $html . ‘
‘ : $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;
}
上一篇:java设计模式-策略模式