0

我正在尝试组合一个地理检测来改变轻微的语言变量。

我的检测工作正常,但数组检查似乎不起作用,我需要知道它是否来自国家/地区列表。如果我呼应该国家/地区,那么我会得到正确的名称,因此我知道这些部分正在工作。

//Get User Country

$country_arr = array(
    "Canada" => "ca", 
    "United States" => "us", 
    "United Kingdom" => "uk", 
    "Australia" => "au",
    "South Africa" => "za",
    "Unknow" => "shot"
);

$country=visitor_country();

if (in_array($country, $country_arr)) {
    //include ("languages/" . $lang . ".php");
    //echo $country_arr[$country];
    echo "yes
";
} else {
    //include ("languages/en.php");
    echo "no
";
}

echo $country;

拥有一个功能齐全的沙箱,所有相关代码都可以正常工作和食用http://sandbox.onlinephpfunctions.com/code/714d5105012f28cada695a6f11dc61516722e6d7

也不能使用标准的一维数组

$count_array = array("South Africa", "Unknow");
4

4 回答 4

1

使用in_array可以检查值而不是键。

//Get User Country

$country_arr = array(
    "Canada" => "ca", 
    "United States" => "us", 
    "United Kingdom" => "uk", 
    "Australia" => "au",
    "South Africa" => "za",
    "Unknow" => "shot"
);

$country = 'Canada';

if ( isset($country_arr[$country]) )
{
    echo "yes";
}
else
{
    echo "no"; 
}

echo "\n$country";

顺便提一句

请记住,即使使用“常规”数组(没有键),PHP 也具有隐式键,因此要使 in_array正常工作,您必须具备:

$country_arr = array( "Canada", "United States", "United Kingdom" );

最重要的是,国家都有他们的钥匙(但隐含),所以国家在这里是价值观。在您的原始代码国家是关键。

于 2013-11-01T08:35:01.460 回答
1

使用数组array_key_exists代替in_array

//Get User Country

$country = visitor_country();

$country_arr = array(
"Canada" => "ca", 
"United States" => "us", 
"United Kingdom" => "uk", 
"Australia" => "au",
"South Africa" => "za",
"Unknown" => "shot"
);


//$count_array = array("South Africa", "Unknown");

if ( array_key_exists($country, $country_arr) ) {
//include ("languages/" . $lang . ".php");
//echo $country_arr[$country];
echo "yes<br>";
} else {
    //include ("languages/en.php");
    echo "no<br>";
}

echo $country;

对于 in_array 函数,您的$country_arr数组应该是这样的

/* For IN Array */
$country_arr = array(
    "Canada", 
    "United States", 
    "United Kingdom", 
    "Australia",
    "South Africa",
    "Unknown"
);

$count_array = array("South Africa", "Unknow");的不工作,因为$country返回Unknown,你有Unknow与价值不匹配..

于 2013-11-01T08:39:00.540 回答
0

你有一个错字 - Unknow/ Unknown,而且,你不是用 搜索键in_array(),你需要使用array_key_exists()orarray_flip($country_arr)

于 2013-11-01T08:35:10.550 回答
-1

您的 GeoIP 服务返回countryNamecountryCode字段。只需使用countryCode代替,countryName您的代码就可以工作:

if($ip_data && $ip_data->geoplugin_countryCode != null)
    {
        $result = $ip_data->geoplugin_countryCode;
    }
于 2013-11-01T08:36:06.543 回答