【发布时间】:2014-08-29 20:56:57
【问题描述】:
我正在尝试检查 foreach 循环中的值是否在查询的数组中。如果每个值都不在查询中,则应该将其放入 no_email_entered 数组中,但是当我打印出数组时,它会打印出 $user->user_email 中包含的所有值,而它应该只打印去掉 $my_user_mails 数组中不包含的那些。我也尝试了嵌套的 foreach ,但这似乎也不起作用。我会很感激您对此进行第二次观察。
<?php
//Creates empty array for inserts
$no_email_entered = array();
//Make a loop for the emails
foreach( $users_for_site as $user ) {
//Check if each email is in $my_user_emails array, if not add it to the $no_email_entered array
if( ! in_array( $user->user_email, $my_user_emails ) ) {
$no_email_entered[] = $user->user_email;
}
}
?>
$no_email_entered 数组的打印结果为我提供了来自 $users_for_site 的所有电子邮件,这是不正确的。
【问题讨论】:
-
一目了然。不看
$my_user_emails和$users_for_site的内容很难判断。只需在代码中添加一些打印语句,应该很容易看到发生了什么。 -
你知道你可以使用 array_diff() 吗? ch2.php.net/manual/en/function.array-diff.php
-
请仔细检查您的
$my_user_emails数组,它必须是一维数组,例如只是array('email@host1.com', 'email@host2.com', 'email@host3.com')还要注意,对于巨大的数组 in_array() 可能需要很长时间。最好执行$my_user_emails = array_flip($my_user_emails)而不是检查if (isset($my_user_emails[$user->user_email])) -
@CharlotteDunois
array_diff不起作用,因为他循环的数组包含对象,并且他正在与字符串数组进行比较。 -
@Barmar 我不知道他的数组长什么样。他没有提供任何东西。
标签: php arrays if-statement foreach