【问题标题】:Remove duplicate values in php array list删除php数组列表中的重复值
【发布时间】:2014-09-24 14:56:43
【问题描述】:

我创建了一个带有 3 个复选框的表单。每个复选框对应于数据库中的邮件列表。当我选中 2 个复选框时,我可能会得到重复的值。我已尝试使用 PHP 函数 array_unique() 和 jQuery.unique() 函数从数组中删除所有重复的电子邮件地址。

jQuery:

<script>
$("#sendMessage").submit(function(e) {
    $("input[type=checkbox]").each(function() {
        if($(this).is(":checked")) {
            var string = $(this).val();
            $.ajax({
                url: "include/checkbox.inc.php",
                type: "POST",
                data: ({query: string, type: "nonurgent"}),
                dataType:"JSON",
                success: function(data) {
                    keep_cb = data;
                    mail(keep_cb);
                }
            });
        }               
    });
});

包括/checkbox.inc.php:

<?php

// this page checks which mailing group is selected, urgent or non urgent

include("mysession_start.inc.php");
include("db.inc.php");

$testarray = array();
$noDupes = array();

if(isset($_POST['query'])) {
$checkbox_value = $_POST['query'];  
}
if(isset($_POST['type'])) {
$type = $_POST['type'];
}

if($type == "nonurgent") {
$cb_query = "SELECT email_nonurgent FROM client_addresses WHERE $checkbox_value=1";

if($resultq = mysqli_query($link, $cb_query)) {
    $s_count = mysqli_num_rows($resultq);

    while($rowq = $resultq->fetch_array()) {
        $testarray[] = $rowq["email_nonurgent"];
        $noDupes = array_unique($testarray);
    }

    print json_encode($noDupes);
}
} else {
$cb_query = "SELECT email_urgent FROM client_addresses WHERE $checkbox_value=1";    

if($resultq = mysqli_query($link, $cb_query)) {
    $s_count = mysqli_num_rows($resultq);

    while($rowq = $resultq->fetch_array()) {
        $testarray[] = $rowq["email_urgent"];
    }

    print json_encode($testarray);
}
}

?>

单击 2 个复选框后,我可能会收到位于同一数组中的重复电子邮件地址(php 页面中的 $testarray)。我在网上搜索了所有内容,但找不到我做错了什么。

【问题讨论】:

  • 能否包含您尝试使用array_unique() 的代码?不要忘记它返回一个新数组,而不是修改你传入的数组,不像sort()
  • "...从数组中复制电子邮件地址" 您指的是上述代码中的哪个特定变量?
  • 这是很多代码,但看起来你的问题可以表达in just a few words。另外,你应该展示你尝试过的东西,因为我猜不出as simple as array_unique()会出现什么问题。
  • @RandomSeed 应该用几句话来表达。我认为这里出了问题的是,当我选中 2 个复选框时,我得到了 2 个放入一个的数组。我这里可能有一个多维数组,但我不确定。
  • @MarijnvanGool 再次,哪个变量中有重复项

标签: php jquery mysql ajax


【解决方案1】:

我不知道为什么 array_unique 不适合你,但你可以尝试老式的方式,而不是一开始就将它们添加到数组中,例如:

if(!in_array($theEmailAddress, $testarray)){
    // add to array
}
else{
    // more than likely a duplicate
}

出于好奇,array_unique 用过之后会做什么?

【讨论】:

    【解决方案2】:

    可以这样...

    $noDupes = array_map("unserialize", array_unique(array_map("serialize", $testarray)));
    

    【讨论】:

    • 试过了,但服务器仍然向同一个收件人发送 2 封电子邮件
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 2021-04-02
    • 2019-06-12
    • 2013-07-25
    • 2020-03-26
    • 2018-09-26
    • 2014-03-23
    • 2021-04-24
    相关资源
    最近更新 更多