首页 > 解决方案 > 如何将 PHP 表查询列为不可重复的标题

问题描述

我有一个 PHP 表,它包含三个类别: finit "material" disc "discription" size "dimension"

类似的“finit”有不同的“disc”和“size”我想以一种“finit”仅根据数量显示一次的方式显示结果,而“disc”和“size”列在下表中他们相关的“有限”

如果它包含多个描述等,我只能显示一次“finit”。但是列表中的列表没有正确设置。它们直接列在“finit”下并水平列出。

<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
$finit = $rows['finit'];

?>
<table class="table table-striped">
<tr>
    <th>Material</th>
    <th>Discription</th>
    <th>Dimension</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($info)):
    if($rows['finit'] != $finit) {
        echo '<tr><td>'.$rows['finit'].'</td></tr>';
        $finit = $rows['finit'];
    }
    echo'<td>'.$rows['disc'].'</td>';
    echo'<td>'.$rows['size'].'</td>';
endwhile;
?>
</table>
</div> 
</body>
</html>

标签: php

解决方案


您的代码没有生成正确的 HTML,这可以很好地解释演示问题。你也会失去第一个finit价值。查看代码中的注释

<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
// this will cause the first finit to be completely lost
//$finit = $rows['finit'];
$finit = NULL;
?>
<table class="table table-striped">
<tr>
    <th>Material</th>
    <th>Discription</th>
    <th>Dimension</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($info)):
    echo '<tr>';
    if($row['finit'] != $finit) {
        echo '<td>'.$row['finit'].'</td>';
        $finit = $row['finit'];
    } else {
        // when you dont print a finit, you need to output something in that column
        echo '<td>&nbsp;</td>';
    }
    echo '<td>' . $rows['disc'] . '</td>';
    echo '<td>' . $rows['size'] . '</td>';
    echo '</tr>';
endwhile;
?>
</table>

更新

要格式化表格以使finit值始终位于其自己的行上,然后是仅包含其他 2 列的行,您可以尝试。

您必须记住的是,您必须<td>在每行输出相同数量的 ',因此在本例中为 3,除非您使用该colspan="2"属性,但是一旦您有简单的路由工作,请尝试使用。

<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
// this will cause the first finit to be completely lost
//$finit = $rows['finit'];
$finit = NULL;
?>
<table class="table table-striped">
<tr>
    <th>Material</th>
    <th>Discription</th>
    <th>Dimension</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($info)):

    if($row['finit'] != $finit) {
        echo '<tr><td>'.$row['finit'].'</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
        $finit = $row['finit'];
    }
    echo '<tr><td>&nbsp;</td>';
    echo '<td>' . $rows['disc'] . '</td>';
    echo '<td>' . $rows['size'] . '</td>';
    echo '</tr>';
endwhile;
?>
</table>

推荐阅读