php - 如何将列转置为行?

标签 php html mysql

我有以下代码,它从 mysql 数据库中提取一个表并将其转换为 html 中的表。

$query = mysqli_query($link, "select * from timetable Where id = $id and subject != '' order by Day asc, Hour asc "  );
?>
<tr>
    <th>day</th>
    <th>hour</th>
    <th>subject</th>
</tr>
<?php
while ($row = mysqli_fetch_array($query)) {
    echo "<tr>";
    echo "<td>".$row['Day']."</td>";
    echo "<td>".$row['Hour']."</td>";
    echo "<td>".$row['Subject']."</td>";
    echo "</tr>";
}

?>

我正在尝试将日期列转置为沿着表格顶部作为第一行。

这是一个表格示例

day hour subject
0   5   Maths
0   7   Maths
1   0   Maths
1   11  Physics
2   0   Physics
2   9   Maths
3   0   Physics
3   4   Maths
3   6   Physics
3   10  Maths
4   3   Maths
4   8   Physics
5   0   Maths
5   9   Physics
6   1   Maths
6   6   Physics

(请注意,我删除了空值以使该问题的表格更小)

这是我想要的表格的样子

       Day  0     1     2      3     4     5     6 
  hour
     1   physics
     2
     3
     4                      maths
     5          ect 
     6
     7
     8
     9 
     10
     11
     12

最佳答案

您可以先创建此模板

<tr>
<td>Hours\Days</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>

之后

<?php 
for($hour = 1;$hour < 13; $hour++){
    echo "<tr>";
    echo "<td>".$hour."</td>";  
    for($day = 0; $day < 7; $day++){
        while ($row = mysqli_fetch_array($query)) { 
            if($row['Day'] == $day && $row['Hour'] == hour)
                echo "<td>".$row['Subject']."</td>";
            else
                echo "<td></td>";
        }
    }   
    echo "</tr>"
}
?>

也许你可以编写比我更短的代码,但它的方法很简单。

关于php - 如何将列转置为行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42110672/

相关文章:

mysql - 合并mysql中的记录

php - CodeIgniter 不同的功能不起作用

javascript - 我收到 NS_BASE_STREAM_CLOSED 错误时缺少什么?

php - 在 fatal error 发生之前如何处理 "Allowed memory size of X bytes exhausted"?

html - 消除分类多个倾斜图像的末端

html - CSS 样式在 Firefox 中被覆盖

MySQL C API : check if a field exists

php - 在 Woocommerce 中更改删除购物车项目 url

html - <pre> 标记在段落内而不是在单独的行上

mysql - 如何从 date_sub 中排除周末?