日期:2014-05-16  浏览次数:20589 次

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',
    ),
);

function genCate( $data, $pid = 0, $level = 0 ) {
    $string = str_repeat( "--", $level ) . '|';
    static $result = array();
    $result = empty( $level ) ? array() : $result;
    foreach ( $data as $k => $row ) {
        if ( $row['pid'] == $pid ) {
            $row['user_name'] = $string . $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字符串形式:


第三种:返回多维数组形式: