2013-11-24 35 views
0

我對PHP相當陌生,我不知道如何處理數組。這裏是處理,我想添加到我的數據庫中獲得的三個或更多值的多維數組中,然後我想根據時間戳(其中一個值)對它們進行排序。之後,我想顯示所有的排序值。我似乎無法做到這一點,這裏的代碼如何將值插入到多維數組中,然後顯示它們?

$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")'; 

    $results = mysql_query($queryWaitingPatients) or die(mysql_error()); 

    if (mysql_num_rows($results) == 0) { 
     echo '<p>There\'s currently no patient on the waiting list.</p>'; 
     return; 
    } 
    while ($rows = mysql_fetch_array($results)) { 
     extract($rows); 
    //now is the part that I don't know, putting the values into an array 
    } 
    // I'm also not sure how to sort this according to my $TargetTime 
    asort($sortedTimes); 

    //the other part I don't know, showing the values, 

感謝您的幫助!

+1

**僅供參考**'訂單'是[保留字](http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html)。把它換成反引號或用另一個詞,例如「訂單」。 –

+0

爲什麼不在你的sql查詢中使用ORDER BY?這樣數據就已經排序了。 –

回答

0

好吧,讓我們看看你的代碼。首先,你有一個返回結果集的查詢。我不推薦使用mysql_fetch_array,因爲它不僅僅是deprecated(使用mysqli函數代替),但它往往適用於錯誤的代碼。當您的所有密鑰都是數字時,很難弄清楚您所引用的內容。因此,我建議mysqli_fetch_assoc(確保你完全切換到mysqli功能第一,像mysql_connectmysqli_query

其次,我真的不喜歡使用提取物。我們需要直接使用數組。我們如何做到這一點

$myarray = array(); 
while ($rows = mysqlI_fetch_assoc($results)) { 
    $myarray[] = $rows; 
} 
echo $myarray[0]['ArrivalTime']; 

所以我們來看看這個。首先,我們正在構建一個數組。所以我們初始化我們的整體array。然後我們想把行推到這個數組上。這就是$myarray[]所做的。最後,我們推送的數組是關聯的,這意味着該行的所有關鍵字都與查詢的字段名稱匹配。

現在,排序確實需要在您的查詢中完成。因此,讓我們調整您的查詢

$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification 
    FROM exams 
    WHERE CurrentState = "Pending" 
    ORDER BY TargetTime'; 

這樣,你的PHP運行時,你的數據庫現在粗製濫造出來以正確的順序爲您的陣列。不需要排序代碼。

+0

非常感謝!這真的很有見地,很詳細。我仍然是一個新手,因爲我不知道很多功能,這使我有點受限制。至於這種情況,在改變$ myarray之後,我以後需要它 – user3026275

0
$arr = array(); 
while ($rows = mysql_fetch_array($results)) { 
    array_push ($arr, $row); 
} 

print_r($arr); 
0
<?php 
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState 
          FROM exams 
          WHERE CurrentState = "Pending" 
          ORDER BY TargetTime '; 

$results = mysql_query($queryWaitingPatients) or die(mysql_error()); 
    if ($results -> num_rows < 1) 
    { 
     echo '<p>There\'s currently no patient on the waiting list.</p>'; 
    } 
    else 
    { 
    while ($rows = mysqli_fetch_array($results)) 
     { 
     $arrivaltime = $row['ArrivalTime']; 
     $targettime = $row['targettime']; 
     $order = $row['Order']; 
     $classification = $row['Classification']; 
     echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification; 
     } 
    } 
echo "Done!"; 
//or you could put it in a json array and pass it to client side. 
?> 
相關問題