PHP循环最大执行时间

时间:2016-01-24 07:58:36

标签: php loops

我在下面的php文件中有这段代码。 问题是我得到的错误最大执行时间超过了120秒。我无法弄清楚问题,但我认为这可能与我做循环的方式有关。如果我这样做的话,请提前原谅。

<?php

for ($i=0;$i<168;$i++) {  
    $answers[$i] = (int)$data[6+$i];  
}

$A = $B = $C = $D = $E = $F = $G = $H = $I = $J = $K = $L = $M = $N = 0;

for ($z=0;$z<168;$z+14) {
    $A = $A + $answers[0+$z];
    $B = $B + $answers[1+$z];
    $C = $C + $answers[2+$z];
    $D = $D + $answers[3+$z];
    $E = $E + $answers[4+$z];
    $F = $F + $answers[5+$z];
    $G = $G + $answers[6+$z];
    $H = $H + $answers[7+$z];
    $I = $I + $answers[8+$z];
    $J = $J + $answers[9+$z];
    $K = $K + $answers[10+$z];
    $L = $L + $answers[11+$z];
    $M = $M + $answers[12+$z];
    $N = $N + $answers[13+$z];
}

echo "<table border='1'>";
echo    "<tr><td>A</td><td>" . $A . "</td></tr>";
echo    "<tr><td>B</td><td>" . $B . "</td></tr>";
echo    "<tr><td>C</td><td>" . $C . "</td></tr>";
echo    "<tr><td>D</td><td>" . $D . "</td></tr>";
echo    "<tr><td>E</td><td>" . $E . "</td></tr>";
echo    "<tr><td>F</td><td>" . $F . "</td></tr>";
echo    "<tr><td>G</td><td>" . $G . "</td></tr>";
echo    "<tr><td>H</td><td>" . $H . "</td></tr>";
echo    "<tr><td>I</td><td>" . $I . "</td></tr>";
echo    "<tr><td>J</td><td>" . $J . "</td></tr>";
echo    "<tr><td>K</td><td>" . $K . "</td></tr>";
echo    "<tr><td>L</td><td>" . $L . "</td></tr>";
echo    "<tr><td>M</td><td>" . $M . "</td></tr>";
echo    "<tr><td>N</td><td>" . $N . "</td></tr>";
echo "</table>";
echo "<br>";

2 个答案:

答案 0 :(得分:4)

此循环实际上并未递增:

Stretch

应该是:

for ($z=0; $z<168; $z+14) {

for ($z=0; $z<168; $z+=14) { 实际上不会增加​​$z+14

答案 1 :(得分:2)

除了已经提供的解决核心问题的答案之外,如果重复汇总(未经过测试,但应该让您走上正轨),您的代码可以大大简化:

   $totalCount = 168;
   $batchSize = 14;

   for($i=0;$i<168;$i++){  
       $answers[$i] = (int)$data[6+$i];  
   }

   $buffer = array();
   for ($i = 0; $i < $batchSize; $i ++) 
     $buffer[$i] = 0;

   for ($z=0; $z<168; $z += $batchSize) {
       for ($i = 0; $i < $batchSize; $i ++) {
           $buffer[$i] += $answers[$i + $z]
       }
   }

   echo "<table border='1'>";
   for ($i = 0; $i < $batchSize; $i ++) {
       $colName = chr(65 + $i);             // A has code 65
       echo "<tr><td>$colName</td><td>" . $buffer[$i] . "</td></tr>";
   }
   echo "</table>";
   echo "<br>";

这样可以在将来轻松更改问题数量和/或批次计数(除非您超越Z,这需要更改chr逻辑)