PHP subtraction in a while loop for graph
I have t开发者_如何学编程his code:
$previous = 0;
while($row = mysql_fetch_array($result)){
$difference = $row['steam'] - $previous;
$strXML .= "<set name='".date("G:i:s", strtotime($row["tstamp"])). "' value='".$difference."' color='AFD8F8' />";
$previous = $row['steam'];
}
This code is working great with every result after the first one. If i can explain, $previous starts at 0, so the first block on the bar chart actually comes out at 3334, as 3334 - 0 = 3334, however from then on i get exactly what i want because its doing the math between real values. how can i fix the first result?
Thanks
If you're graphing the changes in values, wouldn't it make more sense to skip the first value? I put a code sample below.
I'm not sure exactly what value you would want for the first run through the loop otherwise.
$previous = 0;
$firstRun = true;
while($row = mysql_fetch_array($result)){
$difference = $row['steam'] - $previous;
if (!$firstRun)
$strXML .= "<set name='".date("G:i:s", strtotime($row["tstamp"])). "' value='".$difference."' color='AFD8F8' />";
$previous = $row['steam'];
$firstRun = false;
}
Depends on your application logic. Giving an alternative to Sam's answer, if $difference
is not set yet, you can set it zero.
$difference = isset($difference) ? $row['steam'] - $previous : 0;
精彩评论