php sql子组列表

时间:2013-05-30 19:48:04

标签: php mysql

我有一个简单的代码,它给了我错误。有人可以帮我解释什么是最好的解决方案。我不只是对解决方案感兴趣而不是解释,因为我一直在努力解决这种类型的列表。我用谷歌搜索了它,但我找不到一个虚拟的解释。

非常感谢

<?php
    // Run a Query
    $result = mysql_query("SELECT * FROM weblinks ORDER BY yeargroup ASC");
    $a=-1;
    while ($row = mysql_fetch_array($result)) {
        if ($row['yeargroup'] == $a) {
            echo "<h2 class=\"class\">Year ".$row['yeargroup']."</h2>";
        } else {                    
            echo "<ul><li>";
            echo "<img src=\"" . $row['img'] . "\"/>";
            echo "<a href=\"".$row['weblink']."\">".$row['webname']."</a> - ".$row['weblink'];
            echo "<div class=\"text\">".$row['content']."</div>";
            echo "</li></ul>";
        }
        $a=$row['yeargroup'];   
    }
?>

修正了拼写错误,谢谢

这应该是

Year 1

Link1
Link2
Link3

Year 2

Link1
Link2
Link3

etc.

1 个答案:

答案 0 :(得分:1)

$a = null;

while ($row = mysql_fetch_array($result)) {
    //check if $a is equal to the current yeargroup
    //if not, output the header and open the list
    if ($row['yeargroup'] <> $a) {
        echo "<h2 class=\"class\">Year ".$row['yeargroup']."</h2>";
        echo "<ul>";
    }

    echo "<li>";
    echo "<img src=\"" . $row['img'] . "\"/>";
    echo "<a href=\"".$row['weblink']."\">".$row['webname']."</a> - ".$row['weblink'];
    echo "<div class=\"text\">".$row['content']."</div>";
    echo "</li>";

    //check if $a is equal to the current yeargroup
    //if not, close the list and set $a to the yeargroup for the loop
    if ($row['yeargroup'] <> $a) {
        echo "</ul>";
        $a = $row['yeargroup'];
    }
}