Home  >  Article  >  Backend Development  >  php递归无限极分门别类

php递归无限极分门别类

WBOY
WBOYOriginal
2016-06-13 11:56:36856browse

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 class="brush:php;toolbar:false">';$result = genCate( $data );print_r( $result );exit;?>


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


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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn