php递归无限极分类

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

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

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

第二种:返回html字符串形式:

function getTreeHtml( $data, $pId ) {
    $html = '';
    foreach ( $data as $k => $v ) {
        if ( $v['pid'] == $pId ) { 
            $html .= "
  • " . $v['user_name']; $html .= getTree( $data, $v['id'] ); $html = $html . "
  • "; } } return $html ? '
      ' . $html . '
    ' : $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;
    }



    你可能感兴趣的:(PHP)