2016-10-03 27 views
1

我使用PHP geoip_country_code_by_name功能从阵列看起来像这样还特别为不同的国家有不同的内容:如果国家不在数组中,如何选择第一个数组?

<?php 

    $content = array(
     'GB' => array(
      'meta_description' => "Description is here", 
      'social_title'  => "Title here", 
      'country_content_js' => "js/index.js", 
     ), 
     'BR' => array(
      'meta_description' => "Different Description is here", 
      'social_title'  => "Another Title here", 
      'country_content_js' => "js/index-2.js", 
     ), 
    ); 

?> 

我如何检查是否用户的国家是数组中,如果没有设置“GB '作为默认?

我用这来检查国家:

$country = (isset($_GET['country']) && !empty($_GET['country']) ? $_GET['country'] : (isset($_SESSION['country']) && !empty($_SESSION['country']) ? $_SESSION['country'] : (isset($_COOKIE['country']) && !empty($_COOKIE['country']) ? $_COOKIE['country'] : geoip_country_code_by_name(ip())))); 
+0

也许你应该考虑[in_array()](http://php.net/手动/ en/function.in-array.php) – Alex

+0

那么,这取决于你如何检查国家是否不在数组中,一种方法是使用三元运算符。 – Epodax

+0

我不知道如何检查该国是否不在阵列中 –

回答

0

首先检查它:我添加了默认的国家代码,一个新的变量。($ defaultCountry = 'GB');

其次:尝试获取国家代码(获取,会话,cookie,
geoip_country_code_by_name或默认分配)。

最后:检查$内容数组(在所在的国家代码),否则返回默认的国家..

$defaultCountry = 'GB'; 
if(isset($_GET['country']) && !empty($_GET['country'])){ 
    $country =$_GET['country']; 
}elseif(isset($_SESSION['country']) && !empty($_SESSION['country'])){ 
    $country =$_SESSION['country']; 
}elseif(isset($_COOKIE['country']) && !empty($_COOKIE['country'])){ 
    $country =$_COOKIE['country']; 
}elseif($value = geoip_country_code_by_name(ip())){ 
    $country = $value; 
}else{ 
    $country = $defaultCountry; 
} 

if(isset($content[$country])){ 
    $country =$content[$country]; 
}else{ 
    $country = $content[$defaultCountry];//Default .. 
} 
+0

谢谢你的回答!我尝试使用这种方法,它给了我这个错误消息:“第4行非法偏移类型”...第4行是我有$内容=数组(GB +>数组(国家阵列在这里)) –

+0

你能分享ip()函数,所以我可以给你完整的代码?! –

+0

是否正常工作..?! –

1

首先检查,如果国家代码是$content数组作为键或不在,如果没有服务第一阵列作为默认值。要检查密钥是否存在阵列或不使用array_key_exists()。 (如果可用)或第一

这样,

$countrycode="IN"; 
if(!array_key_exists($countrycode,$content)) { 
    $countryarray=$content[0]; 
} else { 
    $countryarray=$content[$countrycode]; 
} 

上面的代码将返回国的内容,如果在数组中没有找到。

+0

这只会检查IN是否正确?我需要它执行任何不在数组内的国家 –

+0

创建一个所有国家的数组,并逐个检查每个国家。 –

0

您可以ternary operator

countryArr = array(); 
$countryArr = array_key_exists($code,$content) ? $content[$code] : $content['GB']; 
相关问题