且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查数组中的所有值是否都在数据库中,并存储不在新数组中的值

更新时间:2022-11-01 08:18:47

您的代码似乎有些费解,因此,与其调试它,不如先从一个更加侧重的查询开始,然后从那里开始工作.

Your code seems convoluted, so rather than debug it I started with a more focussed query and worked from there.

基本上,查询会向数据库询问出现在 $ tags 数组中的电子邮件的列表,然后使用 array_diff()查找出现在$ tags中的所有电子邮件,但不在数据库中.

Basically, the query asks the database for a list of emails that appear in your $tags array, then uses array_diff() to find any that appear in $tags, but not in the database.

从那里您可以直接产生输出.

From there you can produce your output directly.

ini_set('display_errors',1);

$mysqli = new mysqli('mysql.lv.local','userName', 'userPassword','schemaName' );

// Assuming the input is a string and not an array, json_decode it.
$tags = '["john.smith@gmail.com", "Jane.doe@gmail.com", "jack.smith@gmail.com","fred.jones@gmail.com"]';
$tags = json_decode($tags);
// switch everything to lower case
$tags = array_map('strtolower', $tags);

// Build and prepare a query with placeholders. Note conversion to lower case
$sql = 'select distinct lower(`mail`) from `emails` where lower(`mail`) in (?'.str_repeat(',?', count($tags)-1).')';
//echo $sql;
$stmt = $mysqli->prepare($sql);

// Bind the values from $tags to the query
$stmt->bind_param(str_repeat('s', count($tags)), ...$tags);
// Execute
$stmt->execute();
// Bind a variable for the result
$stmt->bind_result($email);
// Retrieve the emails in to $dbMails
$dbMails = [];
while ($stmt->fetch()) {
    $dbMails[] = $email;
}
//var_dump($dbMails);
// Anything that's in $tags but not in $dbMails is invalid
$absentEmails = array_diff($tags, $dbMails);
//var_dump($absentEmails);

if ($absentEmails) {
    $op= ["validity"=>"Invalid enails", 'emails'=>array_values($absentEmails)];
} else {
    $op= ["validity"=>"Valid enails"];
}
echo json_encode($op);