ORIGINAL POST
I want to create a navigation menu in PHP with Bootstrap 4. Problem is that one of the \'s is not right (the on
I added menu to the database and check if it's 0 or 1. I have dropped the sub-sub menu's, but I will update this post if I add them.
function menu_builder($pdo, $parent_id) {
$sql = $pdo->prepare("SELECT * FROM menus");
if ($sql->execute()) {
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$array[$row['parent_id']][] = $row;
}
main_menu($array);
}
}
function main_menu ($array, $parent_id = 0) {
if (!empty($array[$parent_id])) {
foreach ($array[$parent_id] as $item) {
if ($item['menu'] == '0') {
echo " - " . PHP_EOL;
echo " " . $item['menu_naam'] . "" . PHP_EOL;
main_menu($array, $item['id']);
echo "
" . PHP_EOL;
}
elseif ($item['menu'] == '1') {
echo " - " . $item['menu_naam'] . "" . PHP_EOL;
sub_menu($array, $item['id']);
echo "
" . PHP_EOL;
}
}
//echo "EDIT: To have sub-menu's the code looks like this and you need the following css too.
function menu_builder($pdo, $parent_id) {
$sql = $pdo->prepare("SELECT * FROM menus");
if ($sql->execute()) {
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$array[$row['parent_id']][] = $row;
}
main_menu($array);
}
}
function main_menu ($array, $parent_id = 0) {
if (!empty($array[$parent_id])) {
foreach ($array[$parent_id] as $item) {
if ($item['menu'] == '0') {
echo " " . PHP_EOL;
echo " " . $item['menu_naam'] . "" . PHP_EOL;
main_menu($array, $item['id']);
echo " " . PHP_EOL;
}
elseif ($item['menu'] == '1') {
echo " ". PHP_EOL;
echo " " . $item['menu_naam'] . "" . PHP_EOL;
sub_menu($array, $item['id']);
echo " " . PHP_EOL;
}
}
}
}
function sub_menu ($array, $parent_id) {
if (!empty($array[$parent_id])) {
echo " " . PHP_EOL;
}
}
function sub_sub_menu ($array, $parent_id) {
if (!empty($array[$parent_id])) {
echo " " . PHP_EOL;
}
The CSS you need for the sub-menu's because bootstrap doesn't have support for it by default (https://stackoverflow.com/a/45755948/2877035):
.dropdown-submenu {
position: relative;
}
.dropdown-submenu a::after {
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
.dropdown-submenu .dropdown-menu {
top: 0;
left: 100%;
margin-left: .1rem;
margin-right: .1rem;
}
and the jQuery:
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {
if (!$(this).next().hasClass('show')) {
$(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
}
var $subMenu = $(this).next(".dropdown-menu");
$subMenu.toggleClass('show');
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {
$('.dropdown-submenu .show').removeClass("show");
});
return false;
});