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

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 "

";
showCategoryTree($categories, 0);

} catch (PDOException $e) {
die ("Error!: " . $e->getMessage() . "
");
}
function showCategoryTree($categories, $n)
{
if (isset($categories[$n])) {
foreach ($categories[$n] as $category) {

echo str_repeat('|-', $category->level) . $category->categoryName ."
";

showCategoryTree($categories, $category->id);
}
}
return;
}
```

显示

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

    A+
发布日期:2021年01月13日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: