php中使用递归显示层级结构

发布时间:2021-01-13 20:58:55 阅读:1163次

php中使用递归显示层级结构

数据库结构

CREATE TABLE categories (
id int(11) NOT NULL AUTO_INCREMENT,
categoryName varchar(100) NOT NULL,
parentCategory int(11) DEFAULT '0',
level tinyint(1) DEFAULT NULL,
sortInd int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 first 0 0 0
2 second 1 1 0
3 third 2 2 0
4 fourth 3 3 0
5 fifth 0 0 0
6 sixth 5 1 0
7 seventh 6 2 0
8 eighth 7 3 0
9 nineth 4 4 0
10 tenth 0 0 0

$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='blog';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='123456';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";

try {
    $pdo = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    $dbh = null;
    $sql = 'SELECT * FROM `categories` ORDER BY `parentCategory`, `sortInd`';
    $result = $pdo->query($sql, PDO::FETCH_OBJ);
    $categories = [];
    foreach ($result as $category) {
        $categories[$category->parentCategory][] = $category;
    }
    echo "<pre>";
    showCategoryTree($categories, 0);

} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br>");
}
function showCategoryTree($categories, $n)
{
    if (isset($categories[$n])) {
        foreach ($categories[$n] as $category) {
                
                        echo str_repeat('|-', $category->level) . $category->categoryName ."<br>";
                        
            showCategoryTree($categories, $category->id);
        }
    }
    return;
}

显示

first
|-second
|-|-third
|-|-|-fourth
|-|-|-|-nineth
fifth
|-sixth
|-|-seventh
|-|-|-eighth
tenth

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:php中使用递归显示层级结构 出自老鄢博客 | 欢迎分享