以下是一个使用PHP递归实现栏目展示的实例,我们将通过一个简单的栏目数据结构来展示如何递归地获取并展示所有栏目及其子栏目。
1. 栏目数据结构
我们定义一个栏目数组,其中每个栏目可能包含子栏目。

```php
$categories = [
1 => [
'id' => 1,
'name' => '首页',
'children' => [
2 => [
'id' => 2,
'name' => '新闻',
'children' => [
3 => ['id' => 3, 'name' => '国内'],
4 => ['id' => 4, 'name' => '国际']
]
],
5 => [
'id' => 5,
'name' => '关于我们',
'children' => []
]
]
],
6 => [
'id' => 6,
'name' => '产品',
'children' => [
7 => [
'id' => 7,
'name' => '产品1',
'children' => []
],
8 => [
'id' => 8,
'name' => '产品2',
'children' => []
]
]
]
];
```
2. 递归函数
接下来,我们定义一个递归函数来遍历和展示这些栏目。
```php
function displayCategories($categories, $indent = 0) {
foreach ($categories as $category) {
echo str_repeat(' ', $indent) . $category['name'] . '
';
if (!empty($category['children'])) {
displayCategories($category['children'], $indent + 2);
}
}
}
```
3. 使用递归函数
我们调用这个递归函数来展示所有的栏目。
```php
echo "







