排序PHP数组到列 [英] Sorting a PHP Array into Columns
本文介绍了排序PHP数组到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个MySQL表,其中包括以下字段:
I have a mysql table that includes the fields:
名称 - 年 - 说明
Name - Year - Description
我想用一年的顺序显示,但希望通过十年来分成的列。我的PHP技能是pretty较弱,因此我只知道怎么做了很长的路,我做基础上,今年的范围一个单独的查询:
I'd like to display in order by year, but want to split into to columns by decade. My PHP skills are pretty weak, so I only know how to do it the long way where I make a separate query based on the year range:
<?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>";
?>
我知道有一个简单/更有效的方式来做到这一点。任何帮助吗?
I know there's an easy/more efficient way to do this. Any help?
感谢
推荐答案
我会做这样的事情:
$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年的十年中的功能和你不必硬code将其所有的方式。
This way you can easily update the function to show 1800's and 2000's decades and you don't have to hard-code it all the way.
希望它帮助!
这篇关于排序PHP数组到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文