猿问

如何使用 PHP 在下拉菜单中仅显示具有相同 page_id 的元素?如何在 foreach

我有多个下拉菜单,我只想显示与下拉菜单中的主页面具有相同 page_id 的子页面。


我有两个 SQL 表:


'pages' => page_id, page_name; 

'subpages' => subpage_id, page_id, page_name;

当我通过表单插入子页面时,它们获得与所选父页面相同的 page_id。


该问题是,所有的子页面下的每个下拉菜单中显示。我只想在共享相同 page_id 的页面下显示子页面。我想我需要在 foreach 循环中写一个 IF 语句,但不知道该怎么做..


索引.php:


include_once('classes.php');


$page = new Page;

$subpage = new Subpage;


$pages = $page->fetch_all();

$subpages = $subpage->fetch_all();


<?php foreach ($pages as $page) { ?>


<button class="dropdown-btn">

  <?php echo $page['page_name']; ?>

</button>


<div class="dropdown-container">

  <?php foreach ($subpages as $subpage) { ?>


    <a href="../subpage.php?id=<?php echo $subpage['subpage_id']; ?>">

      <?php echo $subpage['subpage_name']; ?>

    </a>


  <?php } ?>

</div>


<?php } ?>

摘要:所有子页面都显示在每个页面下拉列表下 - 我想显示与主页共享 page_id 的子页面。我想我需要IF在 foreach 循环中写一个语句,但不知道该怎么做..


HUWWW
浏览 184回答 1
1回答

肥皂起泡泡

您只能匹配page_id与主页相关的相应节目&nbsp; &nbsp; <button class="dropdown-btn">&nbsp; &nbsp; &nbsp; <?php echo $page['page_name']; ?>&nbsp; &nbsp; </button>&nbsp; &nbsp; <div class="dropdown-container">&nbsp; &nbsp; &nbsp; <?php foreach ($subpages as $subpage) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // match respective page_id show only if its related to main page&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if($subpage['page_id'] == $page['page_id'])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; <a href="../subpage.php?id=<?php echo $subpage['subpage_id']; ?>">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php echo $subpage['subpage_name']; ?>&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; <?php } } ?>&nbsp; &nbsp; </div>&nbsp; &nbsp; <?php } ?>
随时随地看视频慕课网APP
我要回答