首页 > 解决方案 > 调用“in_array”似乎不起作用

问题描述

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

这是我在 View.ctp 中的调用,

foreach($types as $type)
{
    if(in_array(array($carId, $type->type_id), $types))
    {
        echo $this->Html->link(
            'Remove',
            ['controller' => 'cars', 'action' => 'removeType'],
            ['class' => 'btn btn-success']
        );
    }else
    {
        echo $this->Html->link(
            'Add',
            ['controller' => 'cars', 'action' => 'addType'],
            ['class' => 'btn btn-success']
        );
    }

这就是我调用我的数据库的方式:

$typesTable = TableRegistry::getTableLocator()->get("Types");
$types = $typesTable->find('all')->toArray();
$this->set('types', $types);

如果数据库中的 $carId 等于 $typesId,则输出结果应该是一个按钮 Remove,如果不等于 Add,则应该显示按钮。

标签: phpcakephpcakephp-3.0

解决方案


正如函数的PHP 文档所述: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
   }
}

推荐阅读