PHP if语句,用于检查包含数组的列中是否存在值

时间:2013-10-10 07:17:56

标签: php sql

我有一个存储多个邮政编码的字段。 邮政编码列的查询结果可能包含多个邮政编码:90027,90028,90068

我需要一个if语句来检查结果中是否有单个邮政编码

$zipstring = $rows['pool_zip_codes']);

$zipsql = "SELECT `pool_zip_codes` FROM `cases` WHERE `id` = '{$rowid}' AND `pool_zip_codes` IN ('{$zipstring}') ";

$zipqry = mysql_query($zipsql);
$zipresult = mysql_fetch_row($zipqry);

if (($zipresult[0]) == '90068') { 
this zip code is in the list
} else {
not in list
}
};

4 个答案:

答案 0 :(得分:0)

如果我正确地阅读了您的问题,您想要区分

#####

#####,#####,#####...

要执行此操作,只需使用正则表达式检查字段是否与5位数匹配。

if (preg_match("/^\d{5}$/", $zipresult[0])) {
    ...
}

否则,正如其他人所说,使用in_array()。他们没有说的是你必须首先explode()字符串,才能制作一个数组:

$exploded = explode(",", $zipresult[0]);

if (in_array($exploded, "99999")) {
    ....
}

根据您的评论

编辑,您可以使用strpos()

$targetcode = "99999";
$found = array();
foreach ($zipresult as $row) {
    if (strpos($row['pool_zip_codes'], $targetcode) !== false) {
        $found[] = $row;
    }   
}

in_array()

$targetcode = "99999";
$found = array();
foreach ($zipresult as $row) {
    $exploded = explode(",", $row['pool_zip_codes']);
    if (in_array($exploded, $targetcode)) {
       $found[] = $row;
    }
}

答案 1 :(得分:0)

试试这个

$zipresult = mysql_fetch_array($zipqry);

if (($zipresult['pool_zip_codes']) == '90068') {
this zip code is in the list
} else {
not in list
}

答案 2 :(得分:0)

使用in_array()

作为

if (in_array($zipresult[0],$zipresult)) 
{ 
echo "this zip code is in the list" ;
} 
else { 
echo "not in list"; 
} 

答案 3 :(得分:0)

拆分字符串并使用in_array

if (in_array(explode(',', $zipresult[0]),$zipresult)) 
{ 
   #this zip code is in the list
} 
else { 
   #not in list
}