我有一个数组:
$values = array();
与MySQL查询一起:
$query = "SELECT $columns FROM Prices WHERE `key` LIKE '$rows' AND rate LIKE '$rate'";
if($results = $db->query($query)) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$values[] = $row;
}
$results->free();
}
我使用以下代码打印出表格:(我删除了一些表格列)
<?php
if(!count($values)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
} else {
?>
<table>
<thead>
<tr>
<th>Location</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php
foreach ($values as $v) {
?>
<tr>
<td> <?php echo $v->Location; ?> </td>
<td> <?php echo $v->City; ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
我可以从MySQL查询返回数据,并将其打印到表中。但是,有时不需要打印所有列,因为它们没有值。我想隐藏这些专栏。
表格结果可能是
| col 1 | col 2 | col 3 | col 4 |
==================================
| | | 33 | |
| | | 32 | |
并且会变成
| col 3 |
=========
| 33 |
| 32 |
OR
| col 1 | col 2 | col 3 | col 4 |
==================================
| | | | 65 |
| | | | 25 |
会变成
| col 4 |
=========
| 65 |
| 25 |
我的问题是:我如何隐藏空列?
注意:表格数据是通过输入表格从用户填充的。
我很高兴通过css,php或JS
这样做答案 0 :(得分:0)
假设返回的对象具有键的列名,首先遍历第一行值以获取列名并写入TH标记,然后遍历每一行并写出值。
// mocking up values for example
$values = array( (object) array("col_1" => 72, "col_3" => 44, "col_4" => 16), (object) array("col_1" => 51, "col_3" => 87, "col_4" => 34));
// error message if no results
if(!count($values)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
// display results
} else {
?>
<table border="1">
<thead>
<tr>
<?php foreach ($values[0] as $k => $c) { /* loop first row to get column names */ ?>
<th> <?php echo $k; ?> </th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach ($values as $v) { /* loop rows */ ?>
<tr>
<?php foreach ($v as $k => $c) { /* loop columns */ ?>
<td> <?php echo $c; ?> </td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
输出:
| col_1 | col_3 | col_4 |
==========================
| 72 | 44 | 16 |
| 51 | 87 | 34 |