IF和/或表达>不能让它工作

时间:2016-10-21 10:28:16

标签: php if-statement operators

有人可以帮我这个吗?

我试图展示一些与美国或非盟访客分开的内容。我正在对IP进行地理定位,并使用PHP会话(以便用户可以根据需要切换国家/地区)

if (($jsonobj->countryCode == "AU" || $_SESSION['username'] == "AU") && ($jsonobj->countryCode !== "US" || $_SESSION['username'] !== "US"))
{
    echo 'australian content'; 
} 
if (($jsonobj->countryCode == "US" || $_SESSION['username'] == "US") && ($jsonobj->countryCode !== "AU" || $_SESSION['username'] !== "AU")) 
{
    echo 'us content'; 
} 

我无法让它工作 - 基本上我想要通过IP自动显示内容或他们可以手动切换它的灵活性。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

你的条件错了。 它正在同时验证这两个条件。

这可以解决您的问题。

if ($jsonobj->countryCode == "AU" || $_SESSION['username'] == "AU"){
    echo 'australian content';
} 
if ($jsonobj->countryCode == "US" || $_SESSION['username'] == "US"){
    echo 'us content'; 
} 

答案 1 :(得分:0)

您可以在两个字段中搜索单词,字母或短语以决定要显示的内容。如果它包含两者,它将同时显示两者(如果你想要一个或另一个,删除第二个if并将其更改为else)

if((bool)strpos(strtolower($jsonobj->countryCode . $_SESSION['username']), 'au')) {
    // Australlian
}

if((bool)strpos(strtolower($jsonobj->countryCode . $_SESSION['username']), 'us')) {
    // American
}

如果你有多个,你可以创建一个保存编写代码的函数:

function checkDisplay($code) use ($jsonobj) {
    return (bool)strpos(strtolower($jsonobj->countryCode . $_SESSION['username']), $code);
}

然后使用它:

if(checkDisplay('au')) {
   // Australian
} elseif(checkDisplay('us')) {
   // USA
} else {
   // default or error
}

答案 2 :(得分:0)

所以我们......

/**
 * GEO_IP       Session country_code   Result
 *
 * AU           AU                     AU          AU || AU AND
 * AU           US                     US
 * US           US                     US
 * US           AU                     AU          US || AU
 *
 */
if(( $geo_ip_country_code == "AU" || $_SESSION['country_code'] == "AU" ) &&
   ( $geo_ip_country_code == "US" || $_SESSION['country_code'] == "AU" )
) {
    echo 'australian content';
} else {
    echo 'us content';
}

但这里似乎有一种模式!基本上,GEO_IP可能用于初始设置会话国家代码,但它是确定他们选择的国家/地区的会话,因此可以简化上述内容。

注意:如果$ _SESSION [' country_code']已经设置,并且我假设您在第一页上加载了设置的国家/地区,那么您不想更新它。

更好的解决方案

在您设置会话的地方,您可以使用类似的内容......

if(!isset($_SESSION['country_code'])){
        $_SESSION['country_code'] = $geo_ip_country_code;
}

然后,这只是挑选当前会话值

$country_code = $_SESSION['country_code'];

switch(strtolower($country_code)){
    case 'au':
        echo "Aussie Content";
        break;
    case 'usa':
        echo "USA Content";
        break;
    default:
        echo "Sorry you can not access this.";
}
相关问题