grouping by class in groups
Run out of ideas... I need to group all entries form database. There are fields ID, NAME, CLASS, CREATED. Output would look like this:
<h2>3. Class</h2>
<div class="cont">
3rd class entries..
</div>
<h2>8. Class</h2>
<div class="cont">
8th class entries..
</div>
... and more
So if there are entries with class 3, they all go in their own <div>
with their own heading - <h3>
. The s开发者_运维百科ame thing with 8, 9,10, 545,5357 etc. Numbers within <h3>...</h3>
are taken form the table, so they do not come from a counter like $i++
.
How to achieve that? I hope you got my idea.
Something like this will do the trick...
<?php
$rs = mysql_query('select id, name, class, created from mytable order by class ASC');
while( $row = mysql_fetch_assoc($rs)) {
$is_new_class = ( !isset($last_class_num) || ($row['class'] != $last_class_num) );
if( $is_new_class && isset($last_class_num) ) {
echo "</div>";
}
if( $is_new_class ) {
echo "<h2>{$row['class']}. Class</h2>";
echo "<div class=\"cont\">";
}
echo "NAME: {$row['name']}, <br/>";
echo "CREATED: {$row['created']}";
$last_class_num = $row['class'];
}
if( isset($last_class_num) {
echo "</div>";
}
[edit: I originally misunderstood the example given by the OP, so I've updated the answer to fix that. Also, fixed some type-os in my original example. And cleaned up syntax to make it more readable. (sorry if there was any confusion)]
精彩评论