Php 如何按记录只打印一个类别,以及表中该类别下的其他记录?
我在开发过程中遇到了一个很奇怪的问题,解释起来很简单。我有一张分类表,每一种都属于任何类别。让我们看看:Php 如何按记录只打印一个类别,以及表中该类别下的其他记录?,php,mysql,printing,html-table,Php,Mysql,Printing,Html Table,我在开发过程中遇到了一个很奇怪的问题,解释起来很简单。我有一张分类表,每一种都属于任何类别。让我们看看: 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 OR
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>
我得到以下方案(无类别):
Sortiment 3
Sortiment 4
Sortiment 5
Sortiment 1
Sortiment 2
Sortiment 6
但那不是我需要的。我需要以下打印件:
<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>
第一类
Sortiment 3
Sortiment 4
Sortiment 5
第2类
Sortiment 1
第3类
Sortiment 2
Sortiment 6
请注意,这并不关心类别和排序的顺序
<table>
<?php
while ($r = mysql_fetch_array($q)) {
if (header) {
... once write header of category ...
} else {
echo "<tr> <td>" . $r['sortiment'] . "</td> </tr>";
}
}
?>
</table>
如何像上面的方案一样打印出一个特定的类别?试试这个:
使用temp变量比较类别标题
<?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.*已弃用。我需要像上面的方案一样打印出来。
<?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; ?>