所以我想使用PHP来构建导航菜单。
菜单项存储在数据库中......
数据库:
+--------+---------+
| id | int(11) |
+--------+---------+
| title | varchar |
+--------+---------+
| url | varchar |
+--------+---------+
| parent | int(11) |
+--------+---------+
我需要的输出应该如下所示:
期望的输出:
$menu = array
(
array
(
'title' => 'Item One',
'url' => 'item_one.php',
),
array
(
'title' => 'Item Two',
'url' => 'item_two.php',
'children' => array
(
array
(
'title' => 'Item Three',
'url' => 'item_three.php',
),
array
(
'title' => 'Item Four',
'url' => 'item_four.php',
)
)
)
);
构建菜单的功能应该使用类似下面的代码,我不确定我在做什么,我试图使用这样的东西:
这是我的代码:
// Connect to database and fetch result.
$stmt = $db->prepare('SELECT id,parent,title,url FROM nav_menu');
$stmt->execute();
$result= $stmt->fetch(PDO::FETCH_ASSOC);
// Example function that i'm not sure how to use to get the desired output.
function build($level = NULL)
{
$level_id = empty($level) ? 0 : $level->id;
$level = $this->where('parent', $level_id)->orderby('id', 'asc')->find_all();
$menu = new menu;
foreach ($items as $lvl)
{
$menu->add($lvl->title, $lvl->url, $this->build($lvl));
}
return $menu;
}