首页 > Web开发 > 详细

php递归无限极分类

时间:2014-05-09 22:19:32      阅读:603      评论:0      收藏:0      [点我收藏+]

递归无限级分类有几种形式,我这里只举例比较常用的三种:

第一种:返回有排序的数组:

<?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;
}



php递归无限极分类,布布扣,bubuko.com

php递归无限极分类

原文:http://blog.csdn.net/zyb_icanplay7/article/details/25387743

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!