2 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個贊
你快到了。您必須計(jì)算 2 個日期之間的差異并在您的內(nèi)部循環(huán)下方相應(yīng)地分配顏色。條件如下:
$diff = $month[2] - $month[1];
$total += $diff;
if($diff < -2.0){
echo '<td style="color:green">' . $diff . '</td>';
}else if($diff > 2.0){
echo '<td style="color:red">' . $diff . '</td>';
}else{
echo '<td>' . $diff . '</td>';
}
完整代碼:
<?php
$months = array
(
array("Jan",33.6,32.6),
array("Feb",35.6,42.9),
array("Mar",43.1,40.3),
array("Apr",53.2,51.4),
array("May",62.7,68.1),
array("Jun",76.3,72.5),
array("Jul",76.3,77.1),
array("Aug",74.6,78.6),
array("Sep",68,73.2),
array("Oct",57,60.1),
array("Nov",46.7,45.3),
array("Dec",37.7,41.0)
);
echo '<table border = "1">';
echo '<tr><th>Month</th><th>1950 - 2018</th><th>2018</th><th>Difference</th></tr>';
$total = 0;
foreach ($months as $month) {
echo '<tr>';
foreach ($month as $avg) {
echo '<td>' . $avg . '</td>';
}
$diff = $month[2] - $month[1];
$total += $diff;
if($diff < -2.0){
echo '<td style="color:green">' . $diff . '</td>';
}else if($diff > 2.0){
echo '<td style="color:red">' . $diff . '</td>';
}else{
echo '<td>' . $diff . '</td>';
}
echo '</tr>';
}
echo "<tr><td colspan='4'>Total difference : $total</td></tr>";
echo '</table>';

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個贊
用于array_walk將臨時差異添加到每個子數(shù)組:
array_walk($months, function(&$month){
$month[3] = $month[2] - $month[1];
});
然后 $month[3] 將是你的區(qū)別。為了便于閱讀,我將刪除內(nèi)部循環(huán)并每月顯式回顯該行:
foreach ($months as $month) {
echo '<tr>';
echo '<td>' . $month[0] . '</td>';
echo '<td>' . $month[1] . '</td>';
echo '<td>' . $month[2] . '</td>';
echo '<td';
if ($month[3] > 2) {
echo ' style="color: red;"';
}
elseif ($month[3] < -2) {
echo ' style="color: green;"';
}
echo '>' . $month[3] . '</td>';
echo '</tr>';
}
- 2 回答
- 0 關(guān)注
- 130 瀏覽
添加回答
舉報(bào)