【问题标题】:Call "in_array" doesn't seem to be working [duplicate]调用“in_array”似乎不起作用[重复]
【发布时间】:2020-01-14 12:25:03
【问题描述】:

我在 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按钮应该显示。

【问题讨论】:

  • if else 分支不可能同时执行。如果您从两者都获得输出 - 那么您将不止一次使用不同的输入数据集运行此操作。
  • @04FS 我将编辑我的代码,因为它在 foreach 中,但结果仍然不像假设的那样
  • in_array() 似乎在工作3v4l.org/A58fF
  • @vivek_23 我刚刚编辑了我的代码以使其更清晰,抱歉
  • 您是否想查看您的 $types 数组中是否同时存在 $carId$type->type_id?您的 $types 数组实际上是否应该包含一个包含这两个变量的数组?或者您是否想找出这两个变量中的哪一个(如果有)在您的 $types 数组中?

标签: php cakephp cakephp-3.0


【解决方案1】:

正如PHP docsin_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
   }
}

【讨论】:

  • 建议在提供的副本中使用。
  • @mickmackusa 提供的重复项甚至不是我要求的。我不是在数组中搜索重复值,而是在数组中搜索特定值。
  • 我很清楚您的要求。 “我正在尝试查看 $carId 和 $type->type_id 是否都存在于朋友类型的同一 id 示例中。”阅读欺骗页面上的答案。用正确且预先存在的页面结束您的问题并不是一种惩罚,而是利用 Stack Overflow 的海量知识库向您展示如何实现您的目标。
  • @mickmackusa 谢谢,当然可以,但是当我阅读其他问题中提供的答案时,他们正在使用 array_intersect 这可能不是我想要的。
  • @mickmackusa 相同的 id 意味着 $carId 在数据库中具有 $typeId 例如($carId = 2 & $typeId = 4, 2 有 4),而不是因为它们都有 Id 2例如。
【解决方案2】:

你应该在这里传递字符串而不是数组

    $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...
    }
}

【讨论】:

  • 这并不是 OP 所需要的。 OP 需要知道两个字符串同时存在于数组中 - 而不是对不同迭代进行单独检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多