Sort PHP array into columns

I have a mysql table that includes the following fields:

Title - Year - Description

I would like to display in order by year, but want to divide into columns by decade. My PHP skills are pretty weak, so I only know how to do this when I make a separate request based on the range of the year:

<?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 this is a simple and effective way to do this. Any help?

thanks

+6
arrays php mysql
source share
1 answer

I would do something like this:

 $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>"; 

Thus, you can easily update the function to show 1800 and 2000 decades, and you do not need to hard code it completely.

Hope this helps!

+5
source share

All Articles