如下通过php pdo获取mysql菜单表,然后递归实现二级菜单。但是子菜单始终获取不到。
```php
<?php
header('content-type:application/json');
require './connect/pdo_connect_db.php';
function generateMenu($parentId = 0, $depth = 0) {
global $pdo;
$menu = array();
$stmt = $pdo->prepare("SELECT * FROM sys_menu WHERE pid = :parentId");
$stmt->bindParam(':parentId', $parentId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
foreach ($result as $row) {
$item = array(
'id' => $row['id'],
'name' => $row['name'],
);
$menu[] = $item;
$children = generateMenu($row['id'], $depth + 1);
if ($children) {
$item['children'] = $children;
} elseif ($depth > 0) {
// If a menu item has no children, and it's not the top-level menu, stop recursion.
return $menu;
}
}
}
return $menu;
}
$menu = generateMenu();
$jsonMenu = json_encode($menu);
echo $jsonMenu;
?>
当前获取到的只有父菜单:
```php
[
{
"id": "1",
"name": "菜单1"
},
{
"id": "2",
"name": "菜单2"
},
{
"id": "3",
"name": "菜单3"
},
{
"id": "4",
"name": "菜单4"
},
{
"id": "12",
"name": "菜单5"
},
{
"id": "13",
"name": "菜单6"
}
]
mysql sys_menu表: