如何检查项目数组是否仅包含该项目?

时间:2019-03-18 09:40:03

标签: php arrays laravel

$items1 = ['apple', 'tree', 'juice'];
$items2 = ['apple', 'tree'];
$items3 = ['apple'];

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

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

5 个答案:

答案 0 :(得分:4)

//If the array has the only item present    
   if(in_array('apple',$item) && count($item)==1)
    {
    //Do Something
    }

答案 1 :(得分:3)

将您的逻辑与count结合:

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

这将确保您只有一项,并且其值等于要搜索的值。

注意:此处使用array_values是为了重置所有索引,以便我们确保[0]是该值所在。如果愿意,可以使用in_array代替array_values变种。

答案 2 :(得分: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
    });

答案 3 :(得分:0)

您可以使用方法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
}

未经测试,但是您能从中得到启发。

答案 4 :(得分:0)

尝试一下:

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