2013-07-03 63 views
0

這是我的查詢:php如何在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"; 
} 

如何排序由$誕生ASC

+1

如果添加2個月每'birth' $,就不會保持它那種以同樣的方式?另外,如果您只是回覆日期,而不是存儲它們,則不可能返回並採取措施。你能舉一個例子說明你現在正在拿什麼與你想要什麼? – Sean

+0

感謝您的回覆,但我的問題是我的意思是更新 –

+0

@Sean它可能與OB,但絕對不是正確的方法 – Paulpro

回答

5

更改您的查詢增加個月的DB,這樣你就不會需要再訂購返回的行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); 
}); 
+0

謝謝你的回答是正確的,但它的程序的實際情況很多,並且不能用mysql查詢來克服。可能導致返回與PHP? –

+0

感謝兄弟.. :) –