首页 > 代码库 > php递归无限极分类

php递归无限极分类

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

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

<?php

$data = http://www.mamicode.com/array(>

第二种:返回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;
}