繁体   English   中英

in_array()无法与关联数组一起使用

[英]in_array() doesn't work as expected with associative array

我不知道是什么导致了这个问题,但是我将在下面发布代码,然后仔细检查到目前为止我所做的事情以及获得的结果。

$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

'first array entry'不能为NULLFALSE ,唯一起作用的值为TRUE 如果$form_email的值等于没有值的键,则可以为空,如果键具有值并且第一个数组键的值不为TRUE ,则整个操作将以任何方式失败。

重现问题的代码

我不明白发生了什么。 我有两个问题:

  1. 关于如何解决这个问题的任何建议?
  2. 如果您可以帮助我了解发生这种情况的原因-也许我做错了什么?

编辑:

我也尝试了以下方法:

$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

你为什么不使用array_key_exists

if(array_key_exists($form_email, $client_emails)){

}

您正在将$form_email$form_email的值进行$client_emails

if (in_array($form_email, $client_emails)) {

应该将$form_email$client_emails的键(而不是值)进行比较。 -尝试-

if (in_array($form_email, array_keys($client_emails))) {

或检查它们的存在-

if(array_key_exists($form_email, $client_emails)) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM