gpt4 book ai didi

php - 如何在单个 MySQL 查询中检索父子并使用 PHP 显示

转载 作者:行者123 更新时间:2023-11-29 08:54:04 24 4
gpt4 key购买 nike

例如,我有以下 MySQL 表:

parent_id | child_id
---------------------
1 | 4
1 | 3
1 | 5
2 | 8
3 | 7

我想以如下格式打印出父级及其所有子级:

parent     |    child
---------------------
| 4
1 | 3
| 5
---------------------
2 | 8
---------------------
3 | 7

基本上我只想显示父级一次(不同)并使用 PHP 列出其所有子级。是否可以只用一个 SQL 查询来检索上述结果?如果我首先查询父级,然后使用父级 id 递归查询子级,我可以获得上述结果,但这会导致更多的 SQL 查询访问数据库。

或者,我是否检索包含每个parent_id 和children_id 的结果,并使用数组在PHP 中实现上述结果。如果是这样,请告诉我怎么做。

最佳答案

是的。正常选择并使用父级作为数组中的键。

//Query normally
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row["parent_id"]][] = $row["child_id"];
}

或者类似的东西。

编辑

显示部分看起来像这样:

<?php

$result = array(
1 => array(4, 3, 5),
2 => array(8),
3 => array(7)
); //Assuming you get a resultset like this.
$rowIsOpened = false; //Indicates whether a row is currently opened.

//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.

echo <<<HTML
<table>
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping

foreach ($result as $parent => $children) {
echo "<tr>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo ">$parent</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}

}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;

关于php - 如何在单个 MySQL 查询中检索父子并使用 PHP 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439252/

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