简体   繁体   中英

PHP Loop Maximum Execution Time

I have this code segment in my php file below. The problem is that I get the error maximum execution time of 120 seconds exceeded. I can't figure out the problem but I think it may be in the way I did the loop. Pardon in advance if the way I did it is bad.

<?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>";

This loop is not actually incrementing:

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

Should be:

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

$z+14 won't actually increment $z .

Besides the already provided answer, which tackles the core problem, your code can be greatly simplified, if repetitions get aggregated (not tested, but should put you on the right track):

   $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>";

This will allow to change question count and/or batch count easily in the future (unless you go beyond Z , which requires to change chr logic)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM