检查数据数组的重复项

时间:2018-10-04 19:24:53

标签: php arrays

我正在尝试删除来自$row->guestE-mail的电子邮件的所有重复内容

做到这一点的最佳方法是什么?我看到了很多不同的答案

代码:

foreach ($results->data as $row) {
    $emails[] = $row->guestEmail;

    //Check for e-mails to be removed

    $blacklistedEmails = false;

    foreach ($blacklist as $b) {

        if (stripos($row->guestEmail, $b) !== false && date('Y-m-d', strtotime($row->endDate)) == $date) {
            $blacklistedEmails = true;
            ++$blacklistCounts[$b];
            break;
        }
    }

    if (!$blacklistedEmails && date('Y-m-d', strtotime($row->endDate)) == $date) {

        $guests[] = array(
            'FirstName' => $row->guestFirstName,
            'LastName' => $row->guestLastName,
            'email' => $row->guestEmail,
            'country' => $row->guestCountry,
            'check-in_date' => $row->startDate,
            'check-out_date' => $row->endDate,
        );
    }
}

3 个答案:

答案 0 :(得分:0)

您也可以这样做:

$emails = ['email1@gmail.com', 'email2@gmail.com', 'email3@gmail.com', 'email2@gmail.com'];

$new = [];

foreach($emails as $email) {
    if(!in_array($email, $new)) {
        array_push($new, $email);
    }
}

print_r($new);

答案 1 :(得分:0)

  • 创建一个临时变量来存储guestEmail值。
  • 在循环内使用in_array()函数,检查此电子邮件是否已存在于temp变量中。如果是,请忽略进一步的处理,然后继续continue

尝试以下操作:

// temp variable to store all the emails coming in loop
$emails = array();

foreach ($results->data as $row) {

    $guestEmail = $row->guestEmail;

    // check if the guestEmail of this row already exists or not
    if ( in_array($guestEmail, $emails) ) {
        // Duplicate email found
        // continue to next row
        continue;
    }

    // add this row's guestEmail to temp array
    $emails[] = $guestEmail;

    /**
     Here goes your blaclisted emails related code
     **/

}

答案 2 :(得分:0)

只需使用array_unique。无需重新编程该功能。

foreach ($results->data as $row) {
$emails[] = $row->guestEmail;

array_unique($emails); // <--- Insert here

//Check for e-mails to be removed

$blacklistedEmails = false;

foreach ($blacklist as $b) {

    if (stripos($row->guestEmail, $b) !== false && date('Y-m-d', strtotime($row->endDate)) == $date) {
        $blacklistedEmails = true;
        ++$blacklistCounts[$b];
        break;
    }
}

if (!$blacklistedEmails && date('Y-m-d', strtotime($row->endDate)) == $date) {

    $guests[] = array(
        'FirstName' => $row->guestFirstName,
        'LastName' => $row->guestLastName,
        'email' => $row->guestEmail,
        'country' => $row->guestCountry,
        'check-in_date' => $row->startDate,
        'check-out_date' => $row->endDate,
    );
}
}