我尝试设置Cookie,具体取决于用户国家/地区代码是否在数组中可用。
792e9eff-cece-49bc-a696-a0632702e96e
https://api.sportradar.us/ncaamb-t3/games/792e9eff-cece-49bc-a696-a0632702e96e/boxscore.json?api_key=*********** function (error, response, body) {
if(!error && response.statusCode == 200){
var homeName = (data.home.name);
var awayName = (data.away.name);
var homeScore = (data.home.points);
var awayScore = (data.away.points);
if(homeScore > awayScore){
console.log(homeName.toUpperCase() + " WIN!");
}else {
console.log(awayName.toUpperCase() + " WIN!");
}
}
}
现在,如果我的国家/地区代码为$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;
}
}
,则会有效,并会将Cookie "SE"
设置为LanguageCookie
。但是如果我的国家/地区代码在数组中低于swe
,例如"SE"
,它将失败并运行else块(请记住,如果数组中不存在国家/地区代码,则应该运行else块)。
我打破了循环,因为其他它只是继续,最后只运行else块,即使国家代码存在。
如何解决这个问题?
答案 0 :(得分:3)
您无需使用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));
}
答案 1 :(得分:1)
问题是,在循环之后应该执行一次else块 - 如果条件从未满足。这可以通过在循环内设置一个标志来实现。
$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));
}