我试图回显一个数组,在该数组中我想将实际数字与上一个进行比较。结果以%为单位。如果当前字体与前一个字体之间的百分比差异大于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)
答案 0 :(得分:1)
有些事情似乎不是正确的方法,甚至在您的代码中也不正确。尝试使用此方法,如果遇到问题,请不要犹豫,我会尝试进行更新。
_通常,从查询结果中提取行的最佳方法是使用为此专门设计的函数,例如mysqli_fetch_assoc
(它将使用别名或列名作为数组的键)< / p>
_ {implode
从理论上讲如果$result['Diff']
是一个int(实际上您想要一个int),甚至会引发错误,那么在理论上就没用了
_不清楚您是否希望先前值与当前值之间的差是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'];
}
?>