警告:array_key_exists()期望参数2为数组,给定布尔值

ash*_*ajf 0 php

我有一段代码,用于检查数组中存在的给定键.但是当执行这段代码时,我收到错误"警告:array_key_exists()期望参数2是数组,给定布尔值".我是php新手,不知道导致此错误的原因.请帮我.

$structure = imap_fetchstructure($connection, $id, FT_UID);

        if (array_key_exists('parts', $structure))
        {
};
Run Code Online (Sandbox Code Playgroud)

Ray*_*Ray 14

为了防止有人将boolean或null传递给函数,您可以$structure在使用之前添加一个简单的检查以查看是否为数组:

    if (is_array($structure) && array_key_exists('parts', $structure))
    {
       //...magic stuff here 
    }
Run Code Online (Sandbox Code Playgroud)

简单的回答"为什么"你原来的代码被打破是imap_fetchstructure()未找到请求的消息和toand返回false,null0.文档http://php.net/manual/en/function.imap-fetchstructure.php并未指出失败时返回的内容,但很容易猜到.大多数返回对象但无法完成的php函数在失败时返回null或false(当我说失败时我并不是指错误或异常,只是无法做或找不到你提出的任何问题).