简体   繁体   English

MySQL从一列到回显表分组相同的值

[英]mysql grouping same value from one column to echo table

I'm struggling to show the outcome I'm looking for. 我正在努力展示我想要的结果。 I need to create a table which can group the rack column which will be the name of the table and the content is from the layout column is the data for the table. 我需要创建一个表,该表可以对机架列进行分组,机架列将是表的名称,内容来自布局列是该表的数据。


 $sql = ' SELECT  rack, id, GROUP_CONCAT(layout) as grouped_name FROM sorting_items GROUP BY rack ORDER BY rack ASC';

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {


        echo '<td>'.$row['rack'].' </td>';
        echo '<table style=" border: 1px solid black; width:100%"><tr>';
        echo '<td>'.$row['grouped_name'].' </td>'; 
        echo '</tr></table>';
    }
} else {
    echo "0 results";
}
$conn->close();


My table is this 我的桌子是这个

╔══════════╦══════╗
║  layout  ║ rack ║
╠══════════╬══════╣
║  cisco1  ║ case1║
║  cisco2  ║ case1║
║  cisco3  ║ case1║
║  juniper ║ case2║
║  cisco4  ║ case2║
╚══════════╩══════╝

im currently getting this 我目前正在得到这个

╔══════════╦══════════════════════╗
║   case1  ║ cisco1,cisco2,cisco2 ║
╚══════════╩══════════════════════╝
╔══════════╦══════════════════════╗
║   case2  ║ juniper,cisco4       ║
╚══════════╩══════════════════════╝

looking to achieve this with the above code 希望通过以上代码实现这一目标

╔══════════╗     
║  case1   ║ 
╠══════════╣
║  cisco1  ║ 
║  cisco2  ║ 
║  cisco3  ║ 
╚══════════╝

╔══════════╗
║  case2   ║ 
╠══════════╣
║  juniper ║ 
║  cisco4  ║ 
╚══════════╝

It looks like what you actually want in your result data loop is something like this, which splits the grouped_name field on commas and then outputs each value on a separate table row: 看起来您在结果数据循环中实际想要的是这样的东西,它将逗号分隔开grouped_name字段,然后在单独的表行上输出每个值:

while($row = $result->fetch_assoc()) {
    echo '<table style=" border: 1px solid black; width:100%">';
    echo '<tr><th>'.$row['rack'].' </th></tr>';
    foreach (explode(',', $row['grouped_name']) as $name) {
        echo '<tr><td>'.$name.' </td></tr>'; 
    }
    echo '</table>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM