简体   繁体   English

比较多维数组中的键

[英]Compare key in multidimensional array

I'm trying to set a cookie depending on if the users country code is available in an array. 我试图根据用户国家代码在数组中是否可用来设置cookie。

$Countries = array(
    "SE" => "swe",
    "DEU" => "ger",
    "NLD" => "dut",
    "HRV" => "cro",
    "FRA" => "fr",
    "HUN" => "hun",
);

foreach($Countries as $Key => $Value) {
    if($this->Country($_SERVER["REMOTE_ADDR"]) == $Key) {
        setcookie('LanguageCookie', $Value, time()+(10 * 365 * 24 * 60 * 60));
        setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
        break;
    } else {
        setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
        break;
    }
}

Now, If my country code is "SE" it will work and it will set the cookie LanguageCookie to swe . 现在,如果我的国家/地区代码为"SE" ,它将正常工作,并将cookie LanguageCookie设置为swe But if my country code is anything below "SE" in the array, for example "HRV" , it will fail and run the else block (keep in mind that if the country code doesnt exist in the array, it should run the else block). 但是,如果我的国家代码在数组中的"SE"以下,例如"HRV" ,它将失败并运行else块(请记住,如果国家/地区代码不存在于数组中,则应运行else块)。

I break the loop because other it'd just go on and in the end just run the else block, even if the country code exists. 我打破了循环,因为其他循环将继续进行,最后即使国家代码存在,也要运行else块。

How can this be fixed? 如何解决?

You don't need to use a foreach loop to achieve this. 您无需使用foreach循环即可实现此目的。

// Get the country code
$country = $this->country($_SERVER['REMOTE_ADDR']);

// Set cookies
if (isset($countries[$country])) {
    setcookie('LanguageCookie', $countries[$country], time()+(10 * 365 * 24 * 60 * 60));
    setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
} else {
    setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
}

The problem is, the else block should be executed once after the loop - if the condition was never met. 问题是,如果从未满足条件,则else块应在循环后执行一次。 This could be achieved, by setting a flag inside the loop. 这可以通过在循环内设置一个标志来实现。

$found = false;
foreach($Countries as $Key => $Value) {
    if($this->Country($_SERVER["REMOTE_ADDR"]) == $Key) {
        setcookie('LanguageCookie', $Value, time()+(10 * 365 * 24 * 60 * 60));
        setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
        $found = true;
        break;
    }
}
if (!$found) {
    setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM