-4

我想检查将数据输入数据库。检查如下

$implode1 = "apple, orange, banana";

$implode2 = "banana, mango";

如果变量中的香蕉$implode1也包含在变量$implode2中,则应显示警告消息。如果变量的值为空,则执行将被忽略。例子:

$implode1 = "";

$implode2 = "";

如何为上述问题编码?

请帮帮我 :(

4

4 回答 4

0
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";

$implode1Array = explode(", ", $implode1);
$implode2Array = explode(", ", $implode2);

$result = array_intersect($implode1Array, $implode2Array);

if(count($result) > 0) {
    exit('Error!');
}
于 2012-11-21T03:21:33.340 回答
0

通常我会假设 cat 你的意思是连接,但在这里似乎不合适。但是,假设这就是您的意思,您只需检查两个变量中的相同连接字符(逗号),如下所示:

if ( stristr($implode1, ",") && stristr($implode2, ",") ) {
    // error
} else {
    // success, do something
}

但是,假设您的意思是在两个变量中输入相同的项目,在这种情况下是水果,您可以这样检查:

$im1 = explode(",", $implode1);
$im2 = explode(",", $implode2);
foreach($im1 as $i) {
    if ( array_search($i, $im2) ) {
        // error
    } else {
        // success, do something
    }
}

您当然可以在两个字符串中搜索给定值,但我认为这不是您想要的。但假设它是,这里是代码:

$duplicate = "apple"; // the item you are searching for a duplicate of
if ( stristri($implode1, $duplicate) && stristr($implode2, $duplicate) ) {
    // error
} else {
    // success, do something
}
于 2012-11-21T03:26:16.083 回答
0
if (count(array_intersect)) { /* warning */ }
于 2012-11-21T03:27:07.890 回答
0

您可以使用 PHP 的array_intersect函数来获取交集(参见http://php.net/manual/en/function.array-intersect.php):

$arr1 = explode(", ", "apple, orange, banana");
$arr2 = explode(", ", "banana, mango");
$intersection = array_intersect($arr1, $arr2);
if (count($intersection) > 0) {
    echo "WARNING: the lists have a non-empty intersection!";
}
于 2012-11-21T03:28:26.557 回答