0

我试图在平民黄昏时关闭我们的冲浪网络摄像头,但在这段代码底部的 if 语句中遇到了一些困难。我很确定这是一个语法问题,但看不到。

//Sunrise
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise
$sunrise = date_sunrise(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0);
$sunrise = (integer) str_replace(":", "", $sunrise);
// echo "Sunrise: ".$sunrise."</br>";

//Sunset
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise
$sunset = date_sunset(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0);
$sunset = (integer) str_replace(":", "", $sunset);
// echo "Sunset: ".$sunset."</br>";


// get the current date using a 24 digit hour without leading zeros, as an int

$current_time = (Integer) date('Gi');

if ((($current_time >= 0000 && $current_time <= $sunrise) && ($current_time >= $sunset
&& $current_time <= 2359)) && ($_SERVER["REQUEST_URI"] == "/webcams/langland-webcam" 
| $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam" || $_SERVER["REQUEST_URI"] ==
"/webcams/llangennith-webcam" || $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam"))
{
   // Cameras are offline

   return true;

}
4

1 回答 1

1

哎呀。这是一个巨大的if声明。我已经分解了一点:

if (
    (
           ($current_time >= 0000 && $current_time <= $sunrise)
        && ($current_time >= $sunset && $current_time <= 2359)
    //  ^^ Should be `||`
    ) && (
           $_SERVER["REQUEST_URI"] == "/webcams/langland-webcam"
        |  $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam"
    //  ^ Should be `||`
        || $_SERVER["REQUEST_URI"] == "/webcams/llangennith-webcam"
        || $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam"
    )
) {

正如评论的那样,我注意到的第一件事是:您应该||在第一次比较时使用。此外,您稍后会使用单个管道|而不是||.

总的来说,我建议您稍微重构一下这段代码。也许将允许的 URI 移动到一个数组中,然后使用in_array()它来检查它。像这样繁琐if的 s 可能会导致问题——正如您刚刚发现的那样。像这样的东西:

$validUris = array("/webcams/langland-webcam", "/webcams/caswell-webcam", "/webcams/llangennith-webcam", "/webcams/swansea-webcam");
if (in_array($_SERVER["REQUEST_URI"], $validUris)) {
    if (($current_time >= 0000 && $current_time <= $sunrise) || ($current_time >= $sunset && $current_time <= 2359)) {
        // Cameras
        return true;
    }
}
于 2013-02-12T22:50:59.863 回答