if(in_array)没有正确执行

时间:2013-11-01 08:26:52

标签: php

我正在尝试将geodetection放在一起以改变轻微的语言变量。

我检测工作完美,但阵列检查似乎不起作用,我需要知道它是否来自国家列表。如果我回应这个国家,那么我得到了正确的名字,所以我知道这些部分正在运作。

//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

也不使用标准的1维数组

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

4 个答案:

答案 0 :(得分: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" );

以上所有国家都有自己的钥匙(但含蓄),所以各国都是价值观。在原始代码中,国家/地区是关键。

答案 1 :(得分: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与该值不匹配。

答案 2 :(得分:0)

您有一个拼写错误 - Unknow / Unknown,而且,您没有使用in_array()搜索密钥,您需要使用array_key_exists()或{{1} }

答案 3 :(得分:-1)

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

if($ip_data && $ip_data->geoplugin_countryCode != null)
    {
        $result = $ip_data->geoplugin_countryCode;
    }