这是我的查询:

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

08-07 00:47