我有一个包含字段的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>";
?>
我知道有一种简单/更有效的方法可以做到这一点。有什么帮助吗?
感谢
答案 0 :(得分:5)
我会做这样的事情:
$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年的功能,而且您无需一直对其进行硬编码。
希望它有所帮助!