2016-10-03 80 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']; 
相關問題