2014-05-05 87 views
0

我有這個時間表,其中第一個循環的一堆成員從數據庫與while循環。在while裏面,我有一個foreach -loop。但是,如何使整個時間表非常緩慢,我需要一種不同的方法解決這個問題。 現在看起來像什麼。PHP比每個循環更好的解決方案

$sql = mysql_query("SELECT * FROM tblstaff ORDER BY strName ASC"); 

while($row = mysql_fetch_array($sql)) 
    { 
$user_id = $row['intId']; 

$arr = array($one, $two, $three, $four, $five, $six, $seven); 

foreach ($arr as $w) { 
$week = $w;       

$sql_offtime = mysql_query("SELECT tbloffwork.intId, tbloffwork.intWhoId, tbloffwork.strWeek 
FROM tblstaff, tbloffwork 
WHERE tbloffwork.intWhoId = '$user_id' AND tbloffwork.strWeek = '$week'"); 
$rwOff = mysql_fetch_array($sql_offtime); 

$sql_work = mysql_query("SELECT DISTINCT tblstaff.intId as staffId, tblstaff.strName, tblworktable.intId, tblworktable.intWhoId, tblworktable.strElapsed, tblworktable.strNotes 
FROM tblstaff, tblworktable 
WHERE tblworktable.intWhoId = '$user_id' AND tblworktable.strElapsed = '$week'"); 
$rw_work = mysql_fetch_array($sql_work); 

if($rwOff['strWeek'] == $week) { 

$td_stat = "timetable-td-background-yellow"; 

} elseif($rw_work['strElapsed'] != "") { 

$td_stat = "timetable-td-background-green"; 

} else { 

    $td_week = "timetable-td-background-red"; 

} 


if($rw_work['strNotes'] != ""){ 

$notes = "<i class='fa fa-pencil-square-o mediumsmall'></i>"; 

} else { $notes = $null; } 

echo "<td align='right' valign='top' id='timetable-td-small-square' class='". $td_week ."''>". $notes ."</td>"; 

} 

} 

有沒有更好的方法來處理這個問題,而不是用foreach方法?

+0

'in_array()'可能? – AbraCadaver

+10

什麼讓它變慢並不是簡單地使用foreach循環;它在循環中所做的事,你沒有準確地發佈。 – developerwjk

+1

...特別是每個用戶的訪問數據庫 –

回答

0

的foreach使得集的副本,你可以使用,而不是

while (list($key, $value) = each($arr)) { 
    echo "Key: $key; Value: $value<br />\n"; 
} 

http://php.net/manual/en/control-structures.foreach.php

+0

謝謝,我試過了,但其結果相同,速度很慢。也許是由於檢查循環內部的數據庫,我不確定。 – MrUnknown

相關問題