我有一个输出年份的简单列。但是输出在一个表中。是否可以根据不同的年份自动分离表格。
<?php
if(mysqli_num_rows($result) > 0){ ?>
<table>
<thead>
<th>Year</th>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$year = $row['year'];
?>
<tr>
<td><?php echo $year; ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
<?php } ?>
这输出
+------+
| year |
+------+
| 2017 |
| 2017 |
| 2018 |
+------+
我正在寻找这个
+------+
| year |
+------+
| 2018 |
+------+
+------+
| year |
+------+
| 2017 |
| 2017 |
+------+
答案 0 :(得分:2)
您的循环只需要在内部检查结果中是否有“年份”更改,并输出HTML表格页脚/标题以启动新表格。请考虑以下伪代码逻辑:
results = query(); // assume ordered by year
year = 0;
first_row = true;
output_HTML_table_header();
while (row = results.next()) {
if (year != row["year"] && !first_row) {
output_HTML_table_footer();
output_HTML_table_header();
}
year = row["year"];
first_row = false;
output_HTML_table_row(row);
}
output_HTML_table_footer();
假设您的数据是:
2016
2017
2017
2018
2019
这产生的输出操作是:
HTML table header
2016 row
HTML table footer
HTML table header
2017 row
2017 row
HTML table footer
HTML table header
2018 row
HTML table footer
HTML table header
2019 row
HTML table footer
“HTML表格标题”输出只是:
<table>
<thead>
<th>Year</th>
</thead>
<tbody>
行是:
<tr>
<td><?php echo $year; ?></td>
</tr>
并且页脚是:
</tbody>
</table>
您只需要在嵌套逻辑中交替/重复它们。
答案 1 :(得分:1)
如果$result
sql按年订购,您可以使用它。
<?php
$year='';
if(mysqli_num_rows($result) > 0){
echo'<table><thead><th>Year</th></thead><tbody>';
while($row = mysqli_fetch_assoc($result)){
//if a new year create new table
if($year!=$row['year']&&$year)echo'</tbody></table><table><thead><th>Year</th></thead><tbody>';
echo'<tr><td>'.$row['year'].'</td></tr>';
//remeber the last year
$year=$row['year'];
}
echo'</tbody></table>';
}
?>