我正在努力展示我想要的结果。我需要创建一个表,该表可以对机架列进行分组,机架列将是表的名称,内容是从布局列中得出的,是该表的数据。
$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();
我的桌子是这个
╔══════════╦══════╗
║ layout ║ rack ║
╠══════════╬══════╣
║ cisco1 ║ case1║
║ cisco2 ║ case1║
║ cisco3 ║ case1║
║ juniper ║ case2║
║ cisco4 ║ case2║
╚══════════╩══════╝
我目前正在获取
╔══════════╦══════════════════════╗
║ case1 ║ cisco1,cisco2,cisco2 ║
╚══════════╩══════════════════════╝
╔══════════╦══════════════════════╗
║ case2 ║ juniper,cisco4 ║
╚══════════╩══════════════════════╝
希望通过以上代码实现这一目标
╔══════════╗
║ case1 ║
╠══════════╣
║ cisco1 ║
║ cisco2 ║
║ cisco3 ║
╚══════════╝
╔══════════╗
║ case2 ║
╠══════════╣
║ juniper ║
║ cisco4 ║
╚══════════╝
答案 0 :(得分:1)
看起来您在结果数据循环中实际想要的是这样的,它将逗号分隔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>';
}