0

我有以下代码: -

$unitedstatess = stristr($ad['country'], 'united states');
            $unitedkingdom = stristr($ad['country'], 'united kingdom');
            $canada = stristr($ad['country'], 'canada');

            if (($unitedstatess != FALSE) OR ($unitedkingdom != FALSE) OR ($canada != FALSE)) { $adsptc4.=$tempcode; }

如果 $ad['country'] 有美国、英国或加拿大,那么它应该通过,否则如果有除上述之外的不同值,它应该进入 else 休息。

示例:- 广告 1 有:(美国;英国)> 那么它应该通过 $adsptc4 广告 2 有:(美国;意大利)> 那么它应该失败。

如果您有不明白的地方,请告诉我。

<?
$ad['country'] = "United States;canada";
$allowed = array(
    'united states' => true,
    'united kingdom' => true,
    'canada' => true
);
$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = false;
foreach($countries as $c) {
    if(isset($allowed[$c]) == FALSE) {
        $found = true;
        break;
    }
}
if($found != true) {
    echo "true";
}
else {
    echo "false";
}
?>

效果很好,如果有任何缺点,请告诉我。

4

1 回答 1

1

您可以将所有“允许”条目存储在一个数组中。并用 array_search() 或 isset() 检查它

数组搜索():

$allowed = array('united states', 'united kingdom', 'canada');
$input = strtolower($ad['country']);
if(array_search($input, $allowed) !== false) {
    //your true code
}
else {
    //your else code
}

伊塞特():

$allowed = array(
    'united states' => true,
    'united kingdom' => true,
    'canada' => true
);
$input = strtolower($ad['country']);
if(isset($allowed[$input])) {
    //true
}
else {
    //false
}

要查找条目,它们必须完全相同,因此 $allowed 中的所有条目都是小写的,并且您的输入 $ad['country'] 更改为小写。

这两种选择都是可能的。我更喜欢第二个,因为我可以提供一些可以处理的额外信息(而不是真的,我可以提供一个特殊的数组或其他东西)。

第二次编辑后:

您可以分解给定的国家并检查每个国家:

$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = true;
foreach($countries as $c) {
    $c = trim($c);
    if(!isset($allowed[$c])) {
        $found = false;
        break;
    }
}
if($found == true) {
    //true
}
else {
    //false
}
于 2011-03-06T15:03:58.860 回答