php loop display sum before loop that does calculation
Is it possible for me to display the sum at the heading before the program runs through?
while (($data = fgetcsv($handle, 1000, ","))) {
if($data[2] != $prevRow2) {
echo '</div>';
if ($prevRow2 != '') {
$stringData .= '</Payment>';
}
echo "<div id=\"row\">";
echo $sum;
$row++;
$sum = 0;
}
else { echo "<div id=\"filler\"></div>";}
foreach ($data as $key => $d) {
if ($key != 1) {
echo "<div class=\"field\">" .$d . "</div>";
}
}
$sum +=$data[6];
echo "<br/>";
echo "<div id=\"filler\"></div>";
$prevRow2 = $data开发者_C百科[2];
}
fclose($handle);
}
You could buffer the output, print out the heading with the sum after the loop ran through, and then output the buffer.
This could be accomplished simply by not echoing but assigning all the values to a variable and echoing that variable at the end - or by using the ob_start, ob_end_flush, etc functions.
So in your example, instead of:
while (true) {
echo "lots of code";
echo "some variable: " . $variable;
$sum = $sum + 1;
}
Write:
while (true) {
$output .= "lots of code";
$output .= "some variable: " . $variable;
$sum = $sum + 1;
}
echo $sum;
echo $output;
精彩评论