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

时间:2010-08-23 01:47:44

标签: php

即使我在函数中为它设置了global,我也会得到第二个参数的以下错误。第二个参数是一个数组。

  

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

$ CAT_ID

Array ( [0] => 76 [1] => 89 [2] => 81 ) 

PHP

for ($x = 0; $x < count($query_cat_id); $x++){
    if(in_array($query_cat_id[$x], $cat_id)){
    //
    }
}

2 个答案:

答案 0 :(得分:3)

将您的代码更改为以下内容:

$cat_id = array( 0 => 76 , 1 => 89 , 2 => 81 ); 

for( $x = 0 , $c = count( $query_cat_id ) ; $x < $c ; $x++ ){
  if( in_array( $query_cat_id[$x] , (array) $cat_id ) ){
    // MATCH FOUND
  }
}

1)如果您的问题中提供的代码是原样的,那么您声明阵列的方式是不寻常的(并且可能有问题), 2)在(array)之前包含$cat_id应确保将其作为数组处理,即使它实际上是一个字符串(它会立即转换为数组以用于该函数)。

我意识到这些建议可能不准确,因为它们是基于您复制并粘贴到SO中的数据,而不是脚本中的实际数据,但它们可能会为您提供一个起点。

可能的替代解决方案

如果代码的目的是比较两个数组,并在发现值在两者之内时执行某些操作,则以下可能是执行此工作的更快方法:

$cat_id = array( 0 => 76 , 1 => 89 , 2 => 81 ); 
//$query_cat_id is assumed as set to an array already

$matched_cat_ids = array_intersect( (array) $query_cat_id , (array) $cat_id );

foreach( $matched_cat_ids as $k => $v ){
  // Perform work required on MATCH for Value "$v"
}

假设您需要为每场比赛执行特定的工作。如果您只是想知道匹配是否已经发生,那么检查count($matched_cat_ids)是否大于零就足够了。

答案 1 :(得分:3)

(array)的第二个参数之前写in_array()