php php检查数组是否包含来自另一个数组的所有数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9655687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:23:08  来源:igfitidea点击:

php check if array contains all array values from another array

phparrays

提问by peter

$all = array
(
    0 => 307,
    1 => 157,
    2 => 234,
    3 => 200,
    4 => 322,
    5 => 324
);
$search_this = array
(
    0 => 200,
    1 => 234
);

I would like to find out if $all contains all $search_this values and return true or false. any idea please?

我想知道 $all 是否包含所有 $search_this 值并返回 true 或 false。有什么想法吗?

回答by orrd

The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:

以前的答案都做了比他们需要的更多的工作。只需使用array_diff。这是最简单的方法:

$containsAllValues = !array_diff($search_this, $all);

That's all you have to do.

这就是你所要做的。

回答by jasonbar

Look at array_intersect().

看看array_intersect()

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

回答by javigzz

A bit shorter with array_diff

使用array_diff短一点

$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');

$containsAllNeeded = 0 == count(array_diff($musthave, $test1));

// this is TRUE

$containsAllNeeded = 0 == count(array_diff($musthave, $test2));

// this is FALSE

回答by James Kyburz

I think you're looking for the intersect function

我想你正在寻找 intersect 函数

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

array_intersect()returns an array containing all values of array1 that are present in all the arguments. Note that keys are preserved.

array_intersect()返回一个数组,其中包含所有参数中出现的 array1 的所有值。请注意,密钥被保留。

http://www.php.net/manual/en/function.array-intersect.php

http://www.php.net/manual/en/function.array-intersect.php

回答by K-Alex

How about this:

这个怎么样:

function array_keys_exist($searchForKeys = array(), $searchableArray) { $searchableArrayKeys = array_keys($searchableArray); return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); }

function array_keys_exist($searchForKeys = array(), $searchableArray) { $searchableArrayKeys = array_keys($searchableArray); return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); }