【问题标题】:How to check whether an array of items contains only this item?如何检查一个项目数组是否只包含这个项目?
【发布时间】:2019-08-08 15:28:30
【问题描述】:
$items1 = ['apple', 'tree', 'juice'];
$items2 = ['apple', 'tree'];
$items3 = ['apple'];

// loop
If ($items[i].containsOnly['apple'])
{
  // do something..
}

在上面的简化示例中,我想获取与给定项目匹配的数组。有没有类似于“containsOnly”的方法?或者最好的方法是什么?

【问题讨论】:

  • 您可以检查该项目是否在集合中以及集合的大小
  • 只是补充一下,你应该改写你的问题,因为你说的是​​collection,但你给了我们数组

标签: php arrays laravel


【解决方案1】:
//If the array has the only item present    
   if(in_array('apple',$item) && count($item)==1)
    {
    //Do Something
    }

【讨论】:

    【解决方案2】:

    将您的逻辑与count 结合起来:

    function containsOnly($a, $v)
    {
        return count($a) === 1 && array_values($a)[0] === $v; 
    }
    

    这将确保您只有一项,并且价值等于您正在搜索的内容。

    注意:这里array_values的用法是重置所有索引,这样我们就可以确保[0]是值所在的位置。如果您愿意,可以使用 in_array 而不是 array_values 变体。

    【讨论】:

      【解决方案3】:

      您可以根据条件创建项目组集合->filter(),然后在通过条件的->each 项目组上运行代码。

      $itemGroups[] = ['apple', 'tree', 'juice'];
      $itemGroups[] = ['apple', 'tree'];
      $itemGroups[] = ['apple'];
      
      collect($itemGroups)
          ->filter(function($items, $key) {
              return count($items) == 1 && in_array('apple', $items);
          })
          ->each(function($items, $key) {
              // do something
          });
      

      【讨论】:

        【解决方案4】:

        您可以使用方法contains。来自Laravel documentation

        $collection = collect(['name' => 'Desk', 'price' => 100]);
        
        $collection->contains('Desk');
        
        // true
        
        $collection->contains('New York');
        
        // false
        

        我认为这个例子相当简单。在您的示例中,它看起来像:

        $collection = $items1->merge($items2)->merge($items3)
        if($collection->contains('apple') && $collection->count() === 1){
          // it contains apple
        }
        

        没有经过测试,但你明白它背后的想法。

        【讨论】:

        • 它似乎没有检查该项目是否是集合中唯一的一项
        • @RomainB。您想检查这是否是该系列中唯一的一个?没明白。我会相应地更新答案。已编辑:基本上您只需要检查集合中的项目数是否为1 以及是否包含apple
        • 我没有,但这似乎是这里的问题^^
        • 在这种情况下,$collection->count() 不会等于 3,因为它没有遍历集合中的每个数组?
        • 我认为他想要的数组带有且仅带有 apple
        【解决方案5】:

        试试这个:

         $items=array_merge($items1,$items2,$items3);
            if (in_array("apple", $items)){
                echo "success";
            }
        

        【讨论】:

        • 这个答案也只会返回 true 数组 items1 和 items2 ,对吗?它应该只适用于数组 items3。 (作为参数的项目和目标数组中的项目应该在数量和值上匹配)。
        猜你喜欢
        • 1970-01-01
        • 2020-08-10
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-20
        • 2011-01-16
        相关资源
        最近更新 更多