4

我有 2 个数组,第二个数组必须包含第一个数组中的所有元素,如何检查?谢谢

For example

array 1: Array ( [0] => Email [1] => 1_Name )
array 2:  Array ( [0] => 1_Name [1] => ) 

In this case it is invalid , as array 2 do not have Email

array 1: Array ( [0] => Email [1] => 1_Name )
array 2:  Array ( [0] => 1_Name [1] => Address [2]=> Email )

 In this case it is valid 
4

4 回答 4

4

使用array_intersect()并测试其输出的长度是否相同:

if (count(array_intersect($arr1, $arr2)) === count($arr1)) {
  // contains all
}

对于键也必须匹配的关联数组,请array_intersect_assoc()改用。

于 2012-05-07T16:55:22.173 回答
2

array_diff在这里很有用。

if( array_diff($array1,$array2)) {
    // array1 contains elements that are not in array2
    echo "invalid";
}
else {
    // all elements of array1 are in array2
    echo "valid";
}
于 2012-05-07T16:56:47.093 回答
1
$invalid = false;
foreach ($array1 as $key => $value) {
    if (!array_key_exists($key, $array2)) {
        $invalid = true;
        break;
    }
}
var_dump($invalid); 
于 2012-05-07T16:55:24.953 回答
0

array_intersect()就像@Michael建议的那样。如果您想知道缺少哪个元素,可以使用array_diff().

于 2012-05-07T16:57:07.087 回答