如何在 PHP 中处理一对多关系


How to handle one to many relation in PHP

如何正确回显一对多查询结果?

对于一个表查询结果,我只会在获取后回显每一行,例如:

+---+------+
|ID | title|
|1  | a    |
|2  | b    |
|3  | c    |
+---+------+
$smtp->bind_result($ID, $title);
while($smtp->fetch()) {
    ''echo here                        
}

但是在使用带有自然连接的查询(下面的示例)后,我不知道如何在 PHP 中将其回显为:"
3 - c - 动作、幻想、军事"

+----+-------+----------+
| ID | title | genre    |
|  3 |   c   | Action   |
|  3 |   c   | Fantasy  |
|  3 |   c   | Military |
+----+-------+----------+

编辑:

让我重新表述这个问题。使用一对多关系时,如何正确显示"多"表中的结果?

这是我目前使用的代码。

//connect to database with self made db class object.
$db = new db();
$db = $db->connect();
$smtp = $db->prepare('select ID, title, description, genre from movie NATURAL JOIN movie_genres WHERE date >= ? AND date < ?');
$smtp->bind_param('ss', $seasonStart, $seasonEnd); //variables defined based on current date.
$smtp->execute();
$smtp->bind_result($ID, $title,$description, $genre));
while($smtp->fetch()) {
    echo '
    <div class="upcoming">
        <div id="upcomingPoster" style="background-image: url(images/' . $ID . '.jpeg)">
            <div>
                <a href="">' . $title . '</a>
            </div>
        </div>
        <div class="upcomingInfo">
            <h2>Description</h2>
            <p class="upcomingInfoDescription">' . $description .'</p>
            <div></div>
            <p>' . $genre . '</p>
        </div>
    </div>';
}

现在使用它时,我的代码基本上是每一行的循环。但我试图把所有类型放在一起,然后再循环到下一部电影。

$stmt->bind_result($ID, $title, $genre);
$movies = array();
while($stmt->fetch()) {
    if (!isset($movies[$ID])){
        $movies[$ID] = array('title'=>$title, 'genres'=>array());
    }
    $movies[$ID]['genres'][] = $genre;
}
foreach ($movies as $ID=>$movie){
    echo $ID . ' - ' . $movie['title'] . ' - ';
    $first = true;
    foreach ($movie['genres'] as $genre){
        if (!first) echo ', ';
        $first = false;
        echo $genre;
    }
    echo '<br />';
}

我不太确定你想做什么,如果我理解的是你想要问的。

我认为您使用的是 PHP-PDO,因此有必要将 sql 语句上的获取结果存储到另一个变量中。这可能看起来像这样:

$smtp->bind_result($ID, $title);
while($result = $smtp->fetch()) {
  var_dump($result);
}

所以现在你应该看到提取的行的数据。