【问题标题】:How to print out only one category by records, and other records under there in table?如何按记录只打印一个类别,而表中的其他记录在哪里?
【发布时间】:2013-12-21 17:11:16
【问题描述】:

我在开发过程中遇到了一个很奇怪的问题,解释起来很简单。我有一个分类表,每个分类都属于任何类别。让我们看看:

Sortiment 1 | Category 2
Sortiment 2 | Category 3 
Sortiment 3 | Category 1 
Sortiment 4 | Category 1 
Sortiment 5 | Category 1 
Sortiment 6 | Category 3

现在,我想按类别订购变得容易了:

SELECT * FROM sortiment ORDER BY category

Sortiment 3 | Category 1 
Sortiment 4 | Category 1 
Sortiment 5 | Category 1 
Sortiment 1 | Category 2
Sortiment 2 | Category 3 
Sortiment 6 | Category 3

如果我们这样做:

<table>
<?php
while ($r = mysql_fetch_array($q)) {
     echo "<tr> <td>" . $r['sortiment'] . "</td> </tr>";
}
?>
</table>

我得到以下方案(无类别):

<table> 
   <tr> 
      <td> Sortiment 3 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 4 </td> 
   </tr>
   <tr> 
      <td> Sortiment 5 </td> 
   </tr>
   <tr> 
      <td> Sortiment 1 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 2 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 6 </td> 
   </tr> 
</table>

但这不是我需要的。我需要以下打印输出:

<table> 
   <tr class="mycategory"> 
      <td> Category 1 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 3 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 4 </td> 
   </tr>
   <tr> 
      <td> Sortiment 5 </td> 
   </tr>
   <tr class="mycategory"> 
      <td> Category 2 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 1 </td> 
   </tr> 
   <tr class="mycategory"> 
      <td> Category 3 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 2 </td> 
   </tr> 
   <tr> 
      <td> Sortiment 6 </td> 
   </tr> 
</table>

注意,这不关心类别和分类的顺序。

<table>
<?php
while ($r = mysql_fetch_array($q)) {
   if (header) {
     ... once write header of category ...
   } else {
     echo "<tr> <td>" . $r['sortiment'] . "</td> </tr>";
   }
}
?>
</table>

如何像上述方案一样打印出 &lt;tr class="mycategory"&gt;Specific category&lt;/tr&gt; 一次?

【问题讨论】:

  • 我需要像上面的方案一样打印出来。

标签: php mysql printing html-table


【解决方案1】:

试试这个:

使用临时变量来比较类别标题;

<?php 
$sortiments = mysql_fetch_array($q,MYSQL_ASSOC);
$tmp_category_header = null;
foreach($sortiments as $sortiment):
   $category  = $sortiment['category_title']; // category name
   $sortiment_label = $sortiment['sortiment_label']; // sortiment
?>   

   <?php if($tmp_category_header == null || $tmp_category_header != $category): ?>
      <tr>
        <th><?php echo $category; ?></th>
     </tr>
   <?php endif; ?>

   <tr>
     <td><?php echo $sortiment_label; ?></td>
   <tr>

   <?php $tmp_category_header = $category; ?>
<?php endforeach; ?>

考虑将您的 mysql_* 更改为 mysqli_* - mysql_* 已弃用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多