How to control which parent menu items are shown?

<ul class="navbar-nav mr-auto">
    <?php foreach($site->links1()->toStructure() as $menu1):	
    if ($p = $menu1->level1()->toPage()): 
    $subItemsCount = $menu1->links2()->toStructure()->count();
?>
    
    <li class="nav-item <?php e($menu1->isOpen(), 'active') ?> <?= $subItemsCount > 0 ? 'dropdown' : '' ?>">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><?= $p->title() ?></a>
        <?php if ($subItemsCount > 0): ?>
           <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <?php foreach ($menu1->links2()->toStructure() as $menu2):
	               <?php if ($p2 = $menu2->level2()->toPage()); ?>
                        <a class="dropdown-item <?php e($p2->isActive(), 'active') ?>" href="<?= $p2->url() ?>"><?= $p2->title() ?></a>
                       <?php endif ?>
              <?php endforeach ?>
           </div>
        <?php endif ?>
    </li>
     <?php endif ?>
    <?php endforeach ?>
</ul>

I cleaned it up and added two if statements regarding the pages, because you didn’t check if they actually exist. I already mentioned it here: How to print field of page or parent page (if it's in parent page)?