您好我尝试列出以第一个字母分隔的类别,但我混淆了如何使用ul和li来设置样式我的查询
$Sql = "SELECT *, COUNT(Cup_Id) AS num
FROM tabcup
INNER JOIN tabcats ON tabcupom.Cat_Id = tabcats.Cat_Id
WHERE tabcup.Cup_Status = 1
GROUP BY tabcup.Cat_Id
ORDER BY tabcat.Cat_Nome
";
$Query= mysql_query($Sql, $Conn) or die (mysql_error($Conn));
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
$Cats .= "<h2>$initial</h2>\n";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>\n";
}
echo $Cats;
返回
<h2> A </h2>
<li> Aaaaaa</li>
<li> Abbbb</li>
<h2> B </h2>
<li> Baaaaa</li>
<li> Bbbbb</li>
结果我试试
<h2> A </h2>
<ul>
<li> Aaaaaa</li>
<li> Abbbb</li>
</ul>
<h2> B </h2>
<ul>
<li> Baaaaa</li>
<li> Bbbbb</li>
</ul>
感谢您的帮助
答案 0 :(得分:1)
在你的循环中添加一个计数器(我的例子中为$i
),以便知道何时添加开始和结束标记,
$i = 0;
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
if ($i != 0) {
$Cats .= "</ul>";
}
$Cats .= "<h2>$initial</h2>\n";
$Cats .= "<ul>";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>\n";
$i++;
}
if ($i > 0) {
$Cats .= "</ul>";
}
答案 1 :(得分:1)
$initial = null;
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
if ($initial) {
$Cats .= "</ul>\n";
}
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
$Cats .= "<h2>$initial</h2>\n<ul>\n";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>\n";
}
if ($Cats) {
$Cats .= "</ul>\n";
}
答案 2 :(得分:0)
试试这段代码:
$ind=0;
$Sql = "SELECT *, COUNT(Cup_Id) AS num
FROM tabcup
INNER JOIN tabcats ON tabcupom.Cat_Id = tabcats.Cat_Id
WHERE tabcup.Cup_Status = 1
GROUP BY tabcup.Cat_Id
ORDER BY tabcat.Cat_Nome
";
$Query= mysql_query($Sql, $Conn) or die (mysql_error($Conn));
while($Rs = mysql_fetch_assoc($Query)){
if($initial !== strtoupper(substr($Rs['Cat_Nome'], 0, 1))) {
$initial = strtoupper(substr($Rs['Cat_Nome'], 0, 1));
if ($ind>0) $Cats.="</ul>\n";
$ind++;
$Cats .= "<h2>$initial</h2>\n";
$Cats.="<ul>";
}
$Cats .= "<li>".$Rs["Cat_Nome"]." (".$Rs["num"].")</li>\n";
}
echo $Cats;
if ($ind>0) echo "</ul>";