3

在下面的代码中有一大段重复的代码。这可以用另一种方式完成,这样代码就不会重复。无论我尝试什么,我都会以同样的方式结束。代码在下面,但在生产版本中要多得多。这东西做国家定位。

if ($GL)
{
 echo 'Managed to find your location';
}else{
 echo "Could not identify GL. Please select from the list below.";
}

这是整个事情(精简)。

$GL = false; //GL is detected using ip to location, and returns boolean
$location = 'UK';//Read from a cookie.

if(isset($location))
{
    echo 'We found a cookie with your location<br />';

    if(array_key_exists($location,$countries))
    {
        echo 'We found a country in the array. Carrying on<br />';
    }else
    {
        echo 'Did not find a country in the array. Looking for GL';
        if ($GL)
        {
            echo 'Managed to find your location. Carrying on';
        }else{
            echo "Could not identify GL. Please select from the list below.";
            }
    }
}
else
{
    echo 'Did not find a location cookie<br />';

    if ($GL)
    {
        echo 'Managed to find your location.Carrying on.';
    }else{
        echo "Could not identify GL. Please select from the list below.";
    }

}
4

3 回答 3

3

你可以做几个简单的解决方案。如:

1)把它放在一个函数中:

function validGL($GL)
{
    if ($GL)
    {
        echo 'Managed to find your location.Carrying on.';
    }
    else
    {
        echo "Could not identify GL. Please select from the list below.";
    }
}

2) 存储一个布尔值以确定是否找到了有效位置:

$GL = false; //GL is detected using ip to location, and returns boolean
$location = 'UK';//Read from a cookie.

$locationFound = false;

if(isset($location))
{
    echo 'We found a cookie with your location<br />';

    if(array_key_exists($location,$countries))
    {
        echo 'We found a country in the array. Carrying on<br />';

        $locationFound = true;
    }
    else
    {
        echo 'Did not find a country in the array. Looking for GL';
    }
}
else
{
    echo 'Did not find a location cookie<br />';
}

if (!$locationFound)
{
    if ($GL)
    {
        $GL_msg = 'Managed to find your location. Carrying on';
    }
    else
    {
        $GL_msg = "Could not identify GL. Please select from the list below.";
    }
}
于 2012-12-20T03:19:45.660 回答
1

你可以这样改写它:

  1. 如果位置通过并在有效的国家/地区列表中找到,请使用它。

  2. 如果没有,如果找到 GL,请使用它。

  3. 如果所有其他方法都失败,则显示列表。

在代码中:

if (isset($location) && array_key_exists($location,$countries)) {
    echo 'We found a country in the array. Carrying on<br />';
} elseif ($GL) {
    echo 'Managed to find your location. Carrying on';
} else {
    echo "Could not identify GL. Please select from the list below.";
}
于 2012-12-20T03:51:19.653 回答
0

您可以将其设为函数,然后使用 GL 变量调用该函数。这样一来,您就不必一遍又一遍地重复相同的内容。

于 2012-12-20T03:16:18.720 回答