Foreach循环从结果中剥离所有数据

时间:2018-10-01 18:58:57

标签: php foreach

在下面的代码中,我创建了一个要删除的电子邮件黑名单,但是当我使用if(stripos($row->guestEmail, $b))

运行时,我得到的是一个空数组

如果删除stripos并使用基本的if语句if($row->guestEmail)运行,它将显示所有数据,包括不在$blacklist中的电子邮件地址。

为什么黑名单中的每个都会剥离所有数据?

$guests = [];
$emails = [];
$blacklist = ['@booking.com', 'N/A', 'n.c@nc.com', 'n.c@nc.com'];
$date = date('Y-m-d');

foreach ($results->data as $row) {
    $emails[] = $row->guestEmail;
    foreach ($blacklist as $b) {
        if (stripos($row->guestEmail, $b) !== false && 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,
            );
        }
    }
}

2 个答案:

答案 0 :(得分:1)

$guests = [];
$emails = [];
$blacklist = ['@booking.com', 'N/A', 'n.c@nc.com', 'n.c@nc.com'];
$date = date('Y-m-d');

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

    //check for all blacklist flags
    $blackListed = false;
    foreach ($blacklist as $b) {
        if (stripos($row->guestEmail, $b) !== false) {
            $blackListed = true;
            break;
        }
    }

    //if all pass and date is good, we're good
    if (!$blackListed && 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,
        );
    }
}

答案 1 :(得分:0)

尝试以下方法:

$guests = [];
$emails = [];
$blacklist = ['@booking.com', 'N/A', 'n.c@nc.com', 'n.c@nc.com'];
$date = date('Y-m-d');

foreach ($results->data as $row) {
    $emails[] = $row->guestEmail;
    foreach ($blacklist as $b) {
        if (stripos($row->guestEmail, $b) === false && 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,
            );
        }
    }
}

存在问题

stripos($row->guestEmail, $b) !== false 

这种情况与您所需要的相反。