【问题标题】:Check if all values in array are in database and store ones that aren't in new array [duplicate]检查数组中的所有值是否都在数据库中并存储不在新数组中的值[重复]
【发布时间】:2021-08-06 07:17:29
【问题描述】:

我有一个看起来像这样的数组 -> ["john.smith@gmail.com", "jane.doe@gmail.com", "jack.smith@gmail.com"]。我想为数据库中存在的每封电子邮件增加 $count。如果它不存在(无效),那么我想将它推送到 $invalidEmails 数组。

之后,我想根据原始数组中的所有电子邮件是否有效来设置我的 $output。如果它们都存在于数据库中,则它们是有效的。我会很感激这方面的帮助,因为我不知道如何从这里开始。它目前不适用于所有情况,例如,如果第一封电子邮件有效但第二封电子邮件无效。

这是我目前所拥有的:

$result = $conn->query("SELECT mail FROM dej_colleagues");
$rows = mysqli_fetch_all($result, MYSQL_ASSOC);
$tags = preg_split("/\,/", $_POST['tags']);
$invalidEmails = array();
$count = 0;

for ($i = 0; $i < sizeof($tags); $i++) {
    $trim_brackets = trim($tags[$i], '[]');
    $trim_quotes = trim($trim_brackets, '"');
    
    foreach($rows as $row) {
        if ($trim_quotes == $row["mail"]) {
            $count += 1;
            break;
        }
    }
    if ($count == 0) {
        array_push($invalidEmails, $tags[$i]);
    }
}
$output = array();
if (sizeof($tags) == $count) {
    $output = array("validity => "valid emails");
}
else {
    $output = array("validity" => "invalid emails", "emails" => $invalidEmails;
}
echo json_encode($output);

【问题讨论】:

  • 很难看出这里应该发生什么。请发布一些示例数据,展示您的起点和预期结果。
  • @TangentiallyPerpendicular 我更新了我的问题。如果您需要任何其他信息,请告诉我

标签: php arrays database logic


【解决方案1】:

您的代码看起来很复杂,所以我没有调试它,而是从更集中的查询开始并从那里开始工作。

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

您可以从那里直接生成输出。

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);

【讨论】:

猜你喜欢
  • 2015-04-12
  • 2021-08-03
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2019-06-07
  • 2020-09-19
  • 1970-01-01
  • 2011-12-14
相关资源
最近更新 更多