MySQL (or PHP?) group results by field data

后端 未结 2 647
一个人的身影
一个人的身影 2020-11-28 15:03

I have a MySQL database that looks similar to this:

ID    Group   Name

1       1       John
2       1       Andrea
3       1       Jack
4       2       Mike         


        
相关标签:
2条回答
  • 2020-11-28 15:31

    This would my solution, althoug is not elegant at all

    <?php
    $dbc = new MySQLI(DBHOST,DBUSER,DBPASS,DB);
    $result = $dbc->query("
    SELECT
    p.Group as 'group',
    GROUP_CONCAT(name) as names
    FROM prueba p
    GROUP BY p.Group
    ");
    ?>
    <table>
    <tr>
        <th>Group</th>
        <th>Name</th>
    </tr>
    <?php while($row = $result->fetch_assoc()){
        $names = split(",",$row["names"]);
    ?>
        <tr>
            <td><?php echo $row["group"] ?> </td>
            <td><?php echo $names[0]; array_shift($names) ?></td>
        </tr>
        <?php foreach( $names as $name){ ?>
            <tr>
                <td></td>
                <td><?php echo $name ?></td>
            </tr>
        <?php } ?>
    <?php } ?>
    </table>
    
    0 讨论(0)
  • 2020-11-28 15:37

    Try this:

    // SQL stuff
    
    $group = null;
    
    while($row = mysql_fetch_array($result))
    {
        if($row['group'] != $group)
        {
            echo $row['group'];
            $group = $row['group'];
        }
    
        $row['name'];
    }
    
    0 讨论(0)
提交回复
热议问题