将结果与上一个结果进行比较,如果差异 Y,则执行 X



我正在尝试回显一个数组,我想将实际数字与前一个进行比较。结果以 % 为单位。如果当前和以前的百分比差异超过 10%,我想将字体着色为红色。

不幸的是,我的整个结果将是红色的,我不知道我可以在哪里放置 10% 的差异。

<?php
#Difference_Query
$Difference_Query = "SELECT (SUM(current) * 100) / ((SUM(cw_1) + SUM(cw_2)) / 2) AS Diff FROM table GROUP BY time";
$Difference = mysqli_query($connect, $Difference_Query);
$previous = 0;
foreach($Difference as $result) {
if($previous > $result['Diff']) {
echo "<font color = 'red'>".number_format($result['Diff'], 2, ",", ".")."%"."</font>"."<br>";
} else {
echo number_format($result['Diff'], 2, ",", "."), "%", "<br>";
}
$previous = $result['Diff'];
}?>

当前视觉对象:

159,09% (red)
196,17% (red)
196,67% (red)
188,56%
188,41%
181,55%
178,15%
175,74%
183,03% (red)
193,31% (red)
224,28% (red)
230,28% (red)

有些不同的事情似乎不是正确的方法,甚至在你的代码中是不正确的。尝试一下,如果您有问题,请随时发表评论,我会尝试更新。

_Usually从查询结果中提取行的最佳方法是使用专门为此制作的函数,例如mysqli_fetch_assoc(将使用别名或列名作为数组的键(

_ 如果$result['Diff']implode是 int(你实际上想要一个 int(,理论上是没有用的,甚至会抛出错误

_it不是很清楚,如果你希望以前和当前之间的差异是电流的 10% 或 10%。该示例显示了第一个

<?php
$Difference_Query = "SELECT (SUM(current) * 100) / ((SUM(cw_1) + SUM(cw_2)) / 2) AS Diff FROM table GROUP BY time";
$Difference = mysqli_query($connect, $Difference_Query);
$previous = 0;
while($result = mysqli_fetch_assoc($Difference)) {
//abs is in case results are not in ascending order; this if will test if current is more than previous+10 or less than previous-10
if(abs($result['Diff'] - $previous) > 10) {
echo "<font color = 'red'>".number_format($result['Diff'], 2, ",", ".")."%"."</font>"."<br>";
} else {
echo number_format($result['Diff'], 2, ",", "."), "%", "<br>";
}
$previous = $result['Diff'];
}
?>

最新更新