gpt4 book ai didi

PHP 和 MySQL 在数据库中查找 parent 的所有子孙

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:11 26 4
gpt4 key购买 nike

我正在努力实现如下目标: Get all child, grandchild etc nodes under parent using php with mysql query results

但我希望在不将所有内容都放入数组中并且不嵌套 if 语句的情况下执行此操作 - 只需一个接一个地完成第一级并且: - 打印项目 - 如果该项目有一个 child 找到它并打印出来 - 如果 child 有 child 找到它并打印出来 - 如果 child 没有 child 向上移动一个级别并寻找下一个 child 或元素,它是 child - 等等......最好是进入 UL LI 列表和子列表集

我的数据库和输出也需要排序,所以它看起来更像这样:

id     name       parent_id     orderby
1 Electronics 0 0
2 Televisions 1 10
3 Portable Electronics 1 20
4 Tube 2 20
5 LCD 2 10
6 Plasma 2 30
7 Mp3 Players 3 30
8 CD Players 3 20
9 2 Way Radios 3 10
10 Flash 7 10

我可以使用 if 语句来做到这一点,但要做到这一点,我需要知道最深的 child 有多少层,以及是否有 7 个层变得困惑。我已经看到它(在上面的链接中)被放入一个多维数组中,但似乎您需要为每个语句嵌套以再次获取数据,这与嵌套 if 解决方案几乎相同。

我很确定答案就在我眼皮底下,但无法在这里或其他地方找到它....

WordPress 似乎有办法做到这一点,但我无法找到那里的代码。

如有任何帮助,我们将不胜感激!

最佳答案

使用以下代码获取数据:

function getChildren($parent) {
$query = "SELECT * FROM tableName WHERE parent_id = $parent";
$result = mysql_query($query);
$children = array();
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$children[$i] = array();
$children[$i]['name'] = $row['name'];
$children[$i]['children'] = getChildren($row['id']);
$i++;
}
return $children;
}

调用这个函数使用

$finalResult = getChildren('*');

James 编辑

只是为了完成这个答案,将结果打印到列表中:

<?php
function printList($array = null) {
if (count($array)) {
echo "<ul>";

foreach ($array as $item) {
echo "<li>";
echo $item['name'];
if (count($item['children'])) {
printList($item['children']);
}
echo "</li>";
}

echo "</ul>";
}
}

printList($finalResult);
?>

关于PHP 和 MySQL 在数据库中查找 parent 的所有子孙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044584/

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