gpt4 book ai didi

php - 如何根据 parent_id 使行与其他行相对应,所有行都来自同一个表

转载 作者:太空宇宙 更新时间:2023-11-03 10:52:02 25 4
gpt4 key购买 nike

我假设这不是简单的方法,但这是我的家庭作业,所以请耐心等待。

我在 Mysql 'menu' 中有一个表,其结构如下:

id - number  
parent_id - number (0 for root)
title - string
link - string

parent_id 与特定行的 ID 链接,在本例中为 product1products

example :  

1 | 0 | about | about.html
2 | 0 | products | products.html
3 | 2 | product1 | product1.html
4 | 2 | product2 | product2.html
5 | 2 | product3 | product3.html

我的目标是制作一组看起来像这样的 ul:

<ul>
<li><a href="about.html"> about </a></li>
<li><a href="products.html"> products </a>
<ul>
<li> <a href="product1.html"> product 1 </a></li>
<li> <a href="product1.html"> product 1 </a></li>
...
</ul>
</li>
...
</ul>

到目前为止,我只把它变成了一个 ul :

<?php
function getAll() {

DBconnect();

$result = mysql_query("SELECT * FROM `menu`");
$listitems = array();

while ($li = mysql_fetch_array($result)) {
$listitems[] = $li;
}
return $listitems;
}

?>
<ul>
<?php
include_once 'functions.php';
$listitems = getAll();
foreach ($listitems as $listitem) {
?>
<li><a href="<?php print $listitem['link']; ?>"><?php print $listitem['title']; ?></a></li>

<?php } ?>
</ul>

这就是问题开始的地方,我不知道如何制作第二个函数或如何调节它以使“子菜单”行成为 ul 中的 >ul.

最佳答案

如果表格中没有大量元素,则很容易解决这个问题。正如 Syed Qarib 用户所说,您可以检查当前项目是否有一些 child 。

关键是使用 parent_id 递归地绘制 html。

这是您需要的代码:

<?php
function getElementsByParentId($parent_id) {

DBconnect();

$query = sprintf("SELECT * FROM `menu` WHERE parent_id=%s",
mysql_real_escape_string($parent_id));

$result = mysql_query($query);

<!-- Alternative using concat
$result = mysql_query("SELECT * FROM `menu` WHERE parent_id=".$parent_id);
-->
$listitems = array();

while ($li = mysql_fetch_array($result)) {
$listitems[] = $li;
}
return $listitems;
}

function paintChildrens($parent_id) {

$listitems = getElementsByParentId($parent_id);

if (count($listitems) > 0) {

?>
<ul>
<?php
foreach($listitems as $listitem) {
?>
<li><a href="<?php print $listitem['link']; ?>"><?php print $listitem['title']; ?></a></li>
<?php
paintChildrens($listitem['id']);
}
?>
</ul>
<?php
}
}

include_once 'functions.php';
paintChildrens(null) ?>

我不是 PHP 开发人员,所以这段代码可能有一些错误,例如空值检查。

关于php - 如何根据 parent_id 使行与其他行相对应,所有行都来自同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23981033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com