简体   繁体   English

警告:in_array()[function.in-array]:第二个参数的数据类型错误

[英]Warning: in_array() [function.in-array]: Wrong datatype for second argument

I am a little rusty in PHP after several years without programming with this language. 几年后我没有使用这种语言编程,我在PHP中有点生疏。

I am fetching data from an array in mySQL using PHP. 我使用PHP从mySQL中的数组中获取数据。

My problem is that at some point I fetch data from a table, using this: 我的问题是,在某些时候我从表中获取数据,使用:

$myArray = mysql_fetch_array( $data ); 

but at some point, the data base may be empty, so $myArray will be null or contain no elements. 但在某些时候,数据库可能是空的,因此$ myArray将为null或不包含任何元素。

Then I have to check if a particular string that is generated on-the-fly is on $myArray. 然后我必须检查在运行中生成的特定字符串是否在$ myArray上。 If it is, another string must be generated and verified if it already exists on $myArray. 如果是,则必须生成另一个字符串并验证它是否已存在于$ myArray中。

$myString = generateString();
if (in_array($myString, $myArray)) {
    $myString = generateString();
}

this code gives me this error: 这段代码给了我这个错误:

Warning: in_array() [function.in-array]: Wrong datatype for second argument 警告:in_array()[function.in-array]:第二个参数的数据类型错误

To prevent in_array from running when $myArray is empty I did this: 为了防止in_array在$ myArray为空时运行,我这样做了:

if (count($myArray) > 0) {
    if (in_array($myString, $myArray)) {
        $myString = generateString();
    }
}

but count is giving me 1 when the array is empty (?)... 但当数组为空时,count会给我一个(?)...

How do I solve that? 我该如何解决?

just another question: $myString is being modified inside the IF that is already testing it. 另一个问题:$ myString正在已经在测试它的IF内修改。 Is this possible in PHP? 这可能在PHP?

Well, if your query failed, you'll have... wait for it... no array! 好吧,如果您的查询失败,您将......等待它......没有数组!

So that in_array call would give you a warning about $myArray not being an array (but false ). 所以in_array调用会给你一个关于$myArray不是数组(但是false )的警告。

You need to check your query for errors, and better yet: 您需要检查查询中的错误,更好的是:

Please, don't use mysql_* functions in new code . 请不要在新代码中使用mysql_*函数 They are no longer maintained and the deprecation process has begun on it. 它们不再被维护,并且已经开始弃用 See the red box ? 看到红色的盒子 Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. 了解准备好的语句 ,并使用PDOMySQLi - 本文将帮助您确定哪些。 If you choose PDO, here is a good tutorial . 如果您选择PDO, 这是一个很好的教程

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

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