当mysql_fetch_assoc时php如何循环排序


how php sorting in looping while mysql_fetch_assoc?

这是我的查询:

$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进行排序

更改查询以增加数据库中的月份数,这样您就不需要再次对行进行排序:

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);
});