Maison > Article > développement back-end > PHP排序疑问
<?phpfunction switchWeek($num){ switch ($num) { case 1: return '星期一'; break; case 2: return '星期二'; break; case 3: return '星期三'; break; case 4: return '星期四'; break; case 5: return '星期五'; break; case 6: return '星期六'; break; case 7: return '星期日'; break; default: return ''; break; }}$con = mysql_connect("localhost","root","") or die('连接失败:'.mysql_error());mysql_select_db("testt");mysql_query('set names utf8');$sql = 'select * from news ';$result = mysql_query($sql);$array = array();while($row = mysql_fetch_array($result,MYSQL_ASSOC)){ $key = date('Y年m月d日',$row['sTime']).' '.switchWeek(date('N',$row['sTime'])); $array[$key][]=$row;}mysql_free_result($result);//var_dump($array);?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>demo</title></head><body><table border='3' style="width: 500px; text-align:center;"><?php foreach ($array as $key => $value) {array_multisort($sTime, SORT_ASC, $value);?> <tr><td colspan='5'><?=$key?></td></tr> <?php foreach ($value as $k => $v) { $sTime[$key] = $v['sTime']; ?> <tr> <td><?=date('H:i',$v['sTime'])?></td> <td><?=$v['title']?></td> <td> <?php if(time() > $v['sTime'] && time() < $v['eTime'] ){ echo '<span style="color: green;">开放中</span>'; } if(time() < $v['sTime']){echo '<span style="color: #999;">暂未开放</span>';} if(time() > $v['eTime']){echo '<span style="color:red ;">已过期</span>';} ?> </td> </tr> <?php } ?><?php }?><tr><td colspan='5'>已过期</td></tr></table></body></html>
先按是否过期进行排序,再按时间进行排序,order by 过期,time
如果仅仅是顺序排列,已过期的在下边未过期的在上边 各自按时间倒序排列
$sql = 'select * from news order by guoqi desc,time desc
如果需要将之分门别类 可以进行两次循环,未过期的列表位置循环一次,已过期的列表位置循环一次,直接在循环输出内容时判断过期与否的字段
如果仅仅是顺序排列,已过期的在下边未过期的在上边 各自按时间倒序排列
$sql = 'select * from news order by guoqi desc,time desc
如果需要将之分门别类 可以进行两次循环,未过期的列表位置循环一次,已过期的列表位置循环一次,直接在循环输出内容时判断过期与否的字段
需要分门别类的循环输出,请问如何实现?有实例吗?
<table border='3' style="width: 500px; text-align:center;"><?php foreach ($array as $key => $value) {array_multisort($sTime, SORT_ASC, $value);?> <tr><td colspan='5'><?=$key?></td></tr> <?php foreach ($value as $k => $v) { if(time() <= $v['eTime']){ $sTime[$key] = $v['sTime']; ?> <tr> <td><?=date('H:i',$v['sTime'])?></td> <td><?=$v['title']?></td> <td> <?php if(time() > $v['sTime'] && time() < $v['eTime'] ){ echo '<span style="color: green;">开放中</span>'; } if(time() < $v['sTime']){echo '<span style="color: #999;">暂未开放</span>';} ?> </td> </tr> <?php } } ?><?php }?><tr><td colspan='5'>已过期</td></tr><?php foreach ($array as $key => $value) {array_multisort($sTime, SORT_ASC, $value);?> <tr><td colspan='5'><?=$key?></td></tr> <?php foreach ($value as $k => $v) { if(time() > $v['eTime']){ $sTime[$key] = $v['sTime']; ?> <tr> <td><?=date('H:i',$v['sTime'])?></td> <td><?=$v['title']?></td> <td> 已过期 </td> </tr> <?php } } ?><?php }?></table>