[英]How can I show only elements with same page_id in my dropdown menu with PHP? How do I write the 'if' statement in foreach loop?
I have multiple dropdown menus and I only want to show subpages that have same page_id as the main pages in the dropdown. 我有多个下拉菜单,我只想显示与下拉菜单中的主页面具有相同page_id的子页面。
I have two SQL tables: 我有两个SQL表:
'pages' => page_id, page_name;
'subpages' => subpage_id, page_id, page_name;
Subpages get same page_id as the chosen parent page has, when I insert them via my form. 当我通过表单插入子页面时,它们与所选父页面具有相同的page_id。
The problem is , all sub-pages are shown under every drop-down menu. 问题是 ,所有子页面都显示在每个下拉菜单下。 I only want to show sub-pages under pages that share the same page_id.
我只想在共享相同page_id的页面下显示子页面。 I suppose I need to write an IF statement in the foreach loop, but not sure how to do that..
我想我需要在foreach循环中编写IF语句,但不确定如何执行此操作。
index.php: index.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 } ?>
Summary: All subpages show under every pages dropdown - I would like to show subpages that share page_id with main pages. 摘要:所有子页面均显示在每个页面下拉菜单下-我想显示与主页共享page_id的子页面。 I suppose I need to write an
IF
statement in the foreach loop, but not sure how to do that.. 我想我需要在foreach循环中编写
IF
语句,但不确定如何执行此操作。
Any help is appreciated! 任何帮助表示赞赏!
You may match respective page_id
show only if its related to main page 仅当其与主页相关时,您才可以匹配相应的
page_id
显示
<button class="dropdown-btn">
<?php echo $page['page_name']; ?>
</button>
<div class="dropdown-container">
<?php foreach ($subpages as $subpage) {
// match respective page_id show only if its related to main page
if($subpage['page_id'] == $page['page_id'])
{
?>
<a href="../subpage.php?id=<?php echo $subpage['subpage_id']; ?>">
<?php echo $subpage['subpage_name']; ?>
</a>
<?php } } ?>
</div>
<?php } ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.