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'] = getTreeArray( $data, $value['id'] );
            $tree[] = $value;
        }
    }
    return $tree;
}



posted @ 2014-06-21 20:08  blfshiye  阅读(304)  评论(0编辑  收藏  举报