PHP计算while循环中两个值之间的差异

时间:2011-01-21 11:00:42

标签: php mysql while-loop

我正在使用PHP从mysql结果输出XML文档,在一列中我有一堆值,但这些是累积值,即:1,3,6,8,12,45等...但是我怎样才能在这个中反映出值之间的差异而不是值本身:

while($row = mysql_fetch_array($result)){
    $strXML .= "<set name='".date("G:i:s", strtotime($row["tstamp"]))
            .  "' value='".$row['steam']."' color='AFD8F8' />";
}

有问题的栏目是“蒸汽”,我怎么能这样做呢?

2 个答案:

答案 0 :(得分:1)

$dataArray = explode(',',$row['steam']);
$dataCount = count($dataArray);
$newArray = array();
for($i = 1; $i < $dataCount; $i++) {
   $newArray[] = $dataArray[$i] - $dataArray[$i-1];
}
$newData = implode(',',$newArray);

答案 1 :(得分:1)

你想这样做吗?

$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'];
}

假设$row['steam']是单个数字,而不是以逗号分隔的列表。