处理while循环并分组MYSQL PHP值 [英] Handling while loop and grouping MYSQL PHP Values

查看:66
本文介绍了处理while循环并分组MYSQL PHP值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张这样的桌子.

    author_id   author_book     rating  
    1           ABC             5
    1           DEF             6
    2           PPP             8
    3           FFF             9

这是我的PHP代码

    <table>
    <tr><td>Author ID</td><td>Author Book</td><td>Rating</td></tr>
    <?php
    $row_data = mysql_query("select * from author_master" );
    while($row = mysql_fetch_array($row_data) ) {
    ?>
    <tr>
    <td><?php echo $row['author_id']; ?></td>
    <td><?php echo $row['author_book']; ?></td>
    <td><?php echo $row['rating']; ?></td>
    </tr>
    <?php } ?>
    </table>

我想做的是将相似的作者分组在同一行中.

What I would like to do is group the similar author in the same row.

输出应如下所示

    Author ID               Author Book         Rating
    1                       ABC                 5
                            DEF                 6

    2                       PPP                 8

    3                       FFF                 9                       

推荐答案

尝试避免使用mysql_*函数.使用mysqli_*.您只需要先将它们分组即可.考虑以下示例:

Try to avoid mysql_* functions. Use mysqli_*. You just need to group them first. Consider this example:

<?php

$link = new mysqli('localhost', 'test', 'test', 'test');
$query = mysqli_query($link, 'SELECT * FROM author_master ORDER BY author_id');
$books = array();
while($row = $query->fetch_assoc()) {
    $books[$row['author_id']][] = $row;
}
?>

<table border="0" cellpadding="10">
    <thead>
        <tr>
            <th>Author ID</th>
            <th>Author Book</th>
            <th>Rating</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($books as $author_id => $values): ?>
            <tr>
                <td><?php echo $author_id; ?></td>
                <td><?php foreach($values as $author_book) {echo $author_book['author_book'] . '<br/>';} ?></td>
                <td><?php foreach($values as $author_book) {echo $author_book['rating'] . '<br/>';} ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

这篇关于处理while循环并分组MYSQL PHP值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆