我有一个 mysql 表,其中包含以下字段:
名称 - 年份 - 描述
我想按年份按顺序显示,但想按十年分成列。我的 PHP 技能相当薄弱,所以我只知道如何根据年份范围进行单独的查询:
<?php
echo "<div><h3>1950</h3>";
$list1950 = mysql_query("SELECT * FROM people WHERE class_year1 > '1949' AND class_year1 < '1960' ORDER BY class_year1, last_name",$db);
while ($thearray = mysql_fetch_array($list1950)) {
echo "<div>$thearray[name] - $thearray[class_year1]<br />$thearray[description]</div>";
}
echo "</div>";
echo "<h3>1960</h3><div>";
$list1960 = mysql_query("SELECT * FROM people WHERE class_year1 > '1959' AND class_year1 < '1970' ORDER BY class_year1, last_name",$db);
while ($thearray = mysql_fetch_array($list1960)) {
echo "<div>$thearray[name] - $thearray[class_year1]<br />$thearray[description]</div>";
}
echo "</div>";
?>
我知道有一种简单/更有效的方法可以做到这一点。有什么帮助吗?
thanks
我会做这样的事情:
$list = mysql_query("SELECT * FROM people ORDER BY class_year1, last_name",$db);
$decade = false;
while ($thearray = mysql_fetch_array($list)) {
// checks if decade is diferent, if so updates and prints it
if( $decade != substr($thearray['class_year'], 2, 1) ) {
// every time we change decade we print a DIV
if($decade!==false) echo "</div>";
$decade = substr($thearray['class_year'], 2, 1);
echo "<div><h3>19".$decade."0</h3>";
}
// prints info for each row
echo "<div>".$thearray['name']." - ".$thearray['class_year1']."<br />".$thearray['description']."</div>";
}
// we print another DIV in the end to close it right
echo "</div>";
这样您就可以轻松更新函数以显示 1800 年代和 2000 年代的几十年,而不必一直对其进行硬编码。
希望能帮助到你!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)