我尝试使用以下函数打印基于唯一列值的几个列表:
<?php
function echoList($country) {
$result = mysql_query("SELECT * FROM `$country`");
$previousClass = '';
while($row = mysql_fetch_array($result)){
$thisClass = $row['class'];
if($thisClass != $previousClass) {
echo '<h3>' . $thisClass.'</h3>';
}
echo '<ul>';
$id = $row['id'];
echo '<li><a href="' . $country . '/'. $id . '">' . $id . '</a></li>';
echo '</ul>';
$previousClass = $thisClass;
}
}
表格是这样的:
id,class,description
1,B,description1
2,B,description2
3,C,description3
4,B,description4
5,B,description5
但这是重复而不是在同一个 UL 中分组,我试图分组但我不知道该怎么做, 我喜欢以这种方式打印:
<h3>B</h3>
<ul>
<li>1</li>
<li>2</li>
<li>4</li>
<li>5</li>
</ul>
<h3>C</h3>
<ul>
<li>1</li>
</ul>
如果有人能帮上忙,谢谢
最佳答案
<?php
function echoList($country) {
$result = mysql_query("SELECT * FROM `$country` order by class, id");
$previousClass = '';
while($row = mysql_fetch_array($result)){
$thisClass = $row['class'];
if($thisClass != $previousClass) {
if ($previousClass) { echo '</ul>'; }
echo '<h3>' . $thisClass.'</h3>';
echo '<ul>';
}
$id = $row['id'];
echo '<li><a href="' . $country . '/'. $id . '">' . $id . '</a></li>';
$previousClass = $thisClass;
}
echo '</ul>';
}
是这样的。此外,不推荐使用 mysql_* 函数。
关于php - 根据唯一列值打印 <li> 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21433772/