PHP比每个循环更好的解决方案

时间:2014-05-05 19:40:50

标签: php arrays loops foreach while-loop

我有这个时间表,其中第一个循环来自数据库的一堆成员和while循环。在while - 循环内部,我有一个foreach - 循环。然而,foreach - 循环使整个时间表变得非常缓慢,我需要一种不同的方法来解决这个问题。 它现在看起来像什么。

$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方法?

1 个答案:

答案 0 :(得分:0)

foreach制作该集的副本,您可以使用而不是

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

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