如何在单个MySQL查询中检索父-子查询并使用PHP显示
例如,我有以下MySQL表:如何在单个MySQL查询中检索父-子查询并使用PHP显示,php,mysql,sql,Php,Mysql,Sql,例如,我有以下MySQL表: parent_id | child_id --------------------- 1 | 4 1 | 3 1 | 5 2 | 8 3 | 7 我想以如下格式打印父级及其所有子级: parent | child --------------------- | 4 1 | 3 |
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查询进入数据库
或者,我是否检索包含每个父id和子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显示它上了。如果我使用foreach($result as$key=>$val){echo$key.-'.$val;},它也会为所有$val打印$key。如何打印不同的$key?您需要一个嵌套的foreach循环。