我不知道是什么导致了这个问题,但我会在下面发布代码,然后查看我到目前为止所做的事情以及我得到的结果。
$client_emails = array(
'email@ex-one.com' => null, // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => null,
);
$form_email = 'email@ex-two.com';
if (!empty($form_email)) {
if (isset($client_emails[$form_email])) {
$client_page = $client_emails[$form_email];
} else { $client_page = null; }
}
if (in_array($form_email, $client_emails)) {
if (!is_null($client_page)) {
echo 'All seems to be good! - ';
echo $client_page;
} else {
echo 'You can not be here.';
}
} else {
echo "For some reason this isn't working... 'in_array' should be finding the email in the array.";
}
上面的代码是我一直在玩的,它不起作用。但是,如果我们将 'first array entry' (comment)
的值从 NULL
更改为 TRUE
,它将起作用,如下所示:
$client_emails = array(
'email@ex-one.com' => true, // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => null,
);
从技术上讲,现在一切正常,但是 TRUE
等于 1
现在我的脚本的其余部分无法正常工作,因为它会将其读取为值1
并回显它。我需要它为 NULL
。
'第一个数组条目'
不能为 NULL
或 FALSE
,唯一有效的值是 TRUE
.如果 $form_email
的值等于一个没有值的键,如果该键有一个值并且没有 TRUE
的值,则它可以为空第一个数组键然后整个事情以任何方式失败。
我不明白发生了什么。我有两个问题:
- 关于如何解决这个问题有什么建议吗?
- 如果你能帮助我理解为什么会这样——也许我做错了什么?
编辑:
我还尝试了以下方法:
$client_emails = array(
'email@ex-one.com' => 'null', // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => 'null',
);
$form_email = 'email@ex-two.com';
if (!empty($form_email)) {
if (isset($client_emails[$form_email])) {
$client_page = $client_emails[$form_email];
} else { $client_page = null; }
}
if (in_array($form_email, $client_emails)) {
if (!empty($client_page) && $client_page != 'null') {
echo 'All seems to be good! - ';
echo $client_page;
} else {
echo 'You can not be here.';
}
} else {
echo "For some reason this isn't working... 'in_array' should be finding the email in the array.";
}
最佳答案
你的问题是你的 if 语句:
if (in_array($form_email, $client_emails))
在这里,您在值 ([NULL, "page_two", "page_three", NULL]
) 中搜索电子邮件,但您需要查看键 (["email@ ex-one.com", ..., "email@ex-four.com"]
), 因此只需使用 array_keys()
,例如
if (in_array($form_email, array_keys($client_emails)))
//^^^^^^^^^^^ See here, so you serach the email in the keys
关于php - in_array() 不能按预期使用关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434465/