我有以下代码,并希望显示一条消息,说明"上埃尔克河娱乐活动 - "那么"安全,谨慎或危险"基于大坝目前的流出量。我以为我有这个工作,但目前的流出超过3000,这应该是危险的,但它仍然显示安全。
$url2 = "http://r7j8v4x4.map2.ssl.hwcdn.net/TFH_R.xml";
$xml2 = simplexml_load_file($url2);
?>
<style>
.discharge-Safe {
font-size: 20px;
background: green;
color: white;
}
.discharge-Caution {
font-size: 20px;
background: yellow;
color: white;
}
.discharge-Dangerous {
font-size: 20px;
background: red;
color: white;
}
</style>
<h4><?php
$discharge = (int) $xml2->RESULTSET[2]->ROW[48]->AVG_HOURLY_DISCHARGE;
$discharge_range = [
'Safe' => [ 'min_range' => 0, 'max_range' => 500 ],
'Caution' => [ 'min_range' => 501, 'max_range' => 799 ],
'Dangerous' => [ 'min_range' => 800, 'max_range' => 9000 ]
];
$discharge_class = function ($value) use ($discharge_range) {
foreach ($discharge_range as $key => $range) {
if (filter_var($value, FILTER_VALIDATE_INT, ['options' => $range]) !== false) {
return $key;
}
}
};
echo '<span class="discharge-'.$discharge_class($discharge).'">Upper Elk River Recreational Activity - '.$discharge_class($discharge).'</span>';
?></h4>
我做了这个改变:
// last item
$discharge = $xml2->RESULTSET[1]->ROW[count($xml2->RESULTSET[1]->ROW)-1]->AVG_HOURLY_DISCHARGE;
$discharge_range = [
'safe' => [ 'min_range' => 0, 'max_range' => 499 ],
'caution' => [ 'min_range' => 500, 'max_range' => 799 ],
'dangerous' => [ 'min_range' => 800, 'max_range' => 10000 ]
];
$discharge_class = function ($value) use ($discharge_range) {
foreach ($discharge_range as $key => $range) {
if (filter_var($value, FILTER_VALIDATE_INT, ['options' => $range]) !== false) {
return $key;
}
}
};
echo '<span class="discharge-'.$discharge_class($discharge).'">Upper Elk River Recreational Activity-'.$discharge.'</span>';
?></h4
现在我得到了上埃尔克河娱乐活动 - 3,845这是正确的流出数字,但没有颜色,根据应该是红色的范围。
如果我将回声更改回原始代码:
echo '<span class="discharge-'.$discharge_class($discharge).'">Upper Elk River Recreational Activity - '.$discharge_class($discharge).'</span>';
?></h4>
我得到上埃尔克河娱乐活动 - ,没有范围名称?
答案 0 :(得分:0)
在PHP中使用数组索引时,它们基于0,所以如果你想要第二个结果集和第48个元素,那么这应该是......
$discharge = (int) $xml2->RESULTSET[1]->ROW[47]->AVG_HOURLY_DISCHARGE;
问题的第二部分是带有逗号的数字。因此,诸如3,845之类的数字导致数字比较出现问题。最简单的方法是删除任何逗号......
$discharge_class = function ($value) use ($discharge_range) {
$value = str_replace(",", "", $value); // Remove commas
foreach ($discharge_range as $key => $range) {
if (filter_var($value, FILTER_VALIDATE_INT, ['options' => $range]) !== false) {
return $key;
}
}
};