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


PHP better solution than for each 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方法?

foreach生成一个集合的副本,您可以使用while代替

while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />'n";
}
http://php.net/manual/en/control-structures.foreach.php