1

嗨,我尝试列出以首字母分隔的类别,但我混淆了如何使用 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>

谢谢你的帮助

4

3 回答 3

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>";
}
于 2013-05-10T22:30:02.577 回答
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";
}
于 2013-05-10T22:30:09.437 回答
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>";
于 2013-05-10T22:33:30.140 回答