这是我的疑问:
$query=mysql_query("select * from people order by birth asc");
while($r=mysql_fetch_assoc($query)){
$birth=$r['birth'];
if($r['addmonth']=="2") {
$birth=date("d-m-Y", strtotime("$birth+2 month")); //additional months on date of birth
}
echo"$r[name] $birth";
}
如何使用$ birth ASC返回的php进行排序
答案 0 :(得分:5)
更改查询以增加数据库的月份,因此您无需再次订购行:
SELECT *, CASE WHEN (addmonth = 2) THEN (birth + INTERVAL 2 MONTH) ELSE (birth) END AS birth_order FROM people ORDER BY birth_order ASC
编辑:
另一种选择是在SQL上检索数组而不进行更改,并使用usort
:
$people = array();
$result = mysql_query("SELECT * FROM people ORDER BY birth ASC");
if ($result) {
while ($r = mysql_fetch_assoc($result)) {
$people []= $r;
}
mysql_free_result($result);
}
$calculate_date = function ($person) {
$date = $person['birth'];
if ($person['addmonth'] == 2) {
$date += '+2 month';
}
return $date;
};
usort($people,function($a,$b)use($calculate_date){
return $calculate_date($a) > $calculate_date($b);
});