调用“ in_array”似乎不起作用

问题描述 投票:0回答:2

我在cakephp中称这种PHP类型为“ in_array”。基本上我正在检查数组中两个字段是否都可用。问题在于,通过这种方法,应该通过检查字段是否在数组中来仅输出一条语句。结果就像跳过数组检查并输出两个不正确的语句。

这是我在View.ctp中的电话,

foreach($types as $type){

   if(in_array(array($carId, $type->type_id), $types))
   {
       //Outputs if they are in the array...
   }else
   {
       //Outputs that they are not in the array...
   }
}

结果输出都是不正确的语句。

php cakephp cakephp-3.0
2个回答
0
投票

作为PHP docs功能状态的in_array()

除非设置了严格的限制,否则使用宽松的比较来搜索大海捞针。

意味着这样做

return in_array(['foo', 'bar'], $arr);

相当于

foreach($arr as $element) {
    if ($element == ['foo', 'bar']) {
        return true;
    }
}
return false;

回到您的代码,您可能想做的是

foreach($types as $type){
   if(in_array($carId, $types) && in_array($type->type_id, $types))
   {
       //both $carId and $type->type_id are in the $types array
   }else
   {
       //either one or both of them are not in the array
   }
}

0
投票

您应该在此处传递String而不是array

    $people = array("Peter", "Joe", "Glenn", "Cleveland");
    $searchStrings = array("Joe","Glenn");

    if(in_array('Joe', $people))
    {
        //Outputs if they are in the array...
    }else
    {
       //Outputs that they are not in the array...
    }

如果要检入数组,则应像这样循环遍历

foreach($searchStrings as $string){
    if(in_array($string, $people))
    {
        //Outputs if they are in the array...
    }else
    {
       //Outputs that they are not in the array...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.