我需要从当前迭代的值中减去上一次迭代的值。在第一次迭代时,不会有先前的值,因此结果应该为零。
例如(期望值)
我的代码如下:
$sel = mysql_query("SELECT RIGHT(serial,4) as value, serial, date
from photodata
where folder='$m' or (serial >= '$cm' && serial <= '$cm2')") or die(mysql_error());
while ($selt=mysql_fetch_array($sel)) {
$value = $selt['value'];
$ser = $selt['serial'];
$dd = $selt['date'];
$rr = $value-$value;
}
我真的确定
$rr
行不通,但我只是尝试过。
只需打印 $rr 作为减值并检查,更改上面代码片段中的一些代码。希望,它能帮助你。
$index = 0;
$oldv = 0;
while ($selt=mysql_fetch_array($sel)) {
$value = $selt['value'];
$ser = $selt['serial'];
$dd = $selt['date'];
if($index==0) {
$oldv = $value;
$index = 1;
}
$rr = $value - $oldv;
echo $rr;
$oldv = $value;
}
我假设您想减去上一行的值。尽管建议您不要使用 mysql_* 函数。
$oldv = 0;
while ($selt=mysql_fetch_array($sel)) {
$oldv = ($oldv == 0) ? $value : $oldv;
$value= $selt['value'];
$ser=$selt['serial'];
$dd=$selt['date'];
echo $subtract = $value - $oldv;
echo $oldv = $value;
}
foreach()
循环并将每一行视为关联数组即可。0
。这是一个基本演示:https://3v4l.org/pJpDT
$sel = <<<SQL
SELECT RIGHT(serial,4) as value,
serial,
date
FROM photodata
WHERE folder=?
OR serial BETWEEN ? AND ?
SQL;
$rows = $mysqli->execute_query($sql, [$m, $cm, $cm2]);
$result = [];
foreach ($rows as $row) {
$result[] = $row + [
'sub' => $row['value'] - ($prev ?? $row['value'])
];
$prev = $row['value'];
}
var_export($result);