当项目不存在时,in_array返回 true


in_array returning true when item does not exist

我有一个表单,允许我的用户根据需要编辑信息。作为此表单的一部分,用户最多可以插入 5 种类型的证明。所有证明都存储在一个单独的表中:

Table: Proof
proofid - primary key
banid - foreign key -> links to banlist table which stores all other information
proof - the link to which contains the proof
type - the type of proof (image, demo, league, ...)
number - the index number of the proof (0 up to 4)

我还有以下代码来更新或插入证明项。它遍历每个字段,并检查数组中当前选定的项是否不为空。如果为 true,它会检查$i是否在存储所选禁止 id 的所有数字的数组中。

对于 banid 237,数组如下所示: Array ( [0] => [1] => 1 )

这实际上表示第一个证明字段为空,但第二个不是,并且表中存在一条记录。

for($i = 0; $i < 5; $i++)
{
    $proof = $checkprooflist[$i];
    $prooftype = $checkprooftypelist[$i];
    if (!empty($proof))
    {                       
        if(!in_array($i, $proofnumberlist))
        {
            $query2 = "INSERT INTO proof (banid, proof, type, number) VALUE ($id, '$proof', '$prooftype', $i)";
            $result2 = mysql_query($query2);
        }
        else
        {
            $query2 = "UPDATE proof SET proof = '$proof', type = '$prooftype' WHERE number = $i AND banid = $id";
            $result2 = mysql_query($query2);
        }
    }           
}

然而,我遇到的问题是,对于上面的数组,if(!in_array($i, $proofnumberlist))行返回 false,因此在 $i = 0 时不输入 if 语句。

它适用于所有其他值(其中 $i = 1,...(等,但不适用于 $i = 0 时。

感谢您

的阅读,感谢您能给我的任何帮助。

乔恩。

你必须使用 in_array()$strict 参数,它是第三个(默认值 = false(。

由于类型杂耍,空字符串可以等于 0,依此类推。$strict参数确保还测试类型。

if (!in_array($i, $proofnumberlist, true))

另一方面,您可以使用 INSERT ... ON DUPLICATE KEY UPDATE 来回避整个in_array检查。

这将使您的代码更清晰一些。见 http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

此数组中没有 0:

Array ( [0] => [1] => 1 )

索引 0 处的元素为 null,而不是 0。您最初从哪里得到这个阵列?