0

例如,我有以下 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

基本上我只想显示父级 ONCE(Distinct) 并用 PHP 列出它的所有子级。是否可以仅使用一个 SQL 查询来检索上述结果?如果我首先查询父母,然后使用父母 ID 递归地查询孩子,我可以获得上述结果,但这将是更多的 SQL 查询访问数据库。

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

4

1 回答 1

2

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

//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;
于 2012-05-03T21:02:43.367 回答