比较数组:第二个数组中包含一个数组(键+值)

时间:2010-07-22 12:31:45

标签: php arrays comparison

我想检查第二个数组中是否包含一个数组, 但是相同的键和相同的值,

(不需要相同,只检查一个数组中的所有键和值是否在第二个中)

直到现在我做的简单事情是:

function checkSameValues($a, $b){

        foreach($a as $k1 => $v1){                                  
            if($v1 && $v1 != $b[$k1]){
                return false;
                break;                                      
            }
        }
        return true;
    }

有更简单(更快)的方法来检查吗?

谢谢

4 个答案:

答案 0 :(得分:3)

我愿意

$array1 = array("a" => "green", "b" => "blue", "c" => "white", "d" => "red");
$array2 = array("a" => "green", "b" => "blue", "d" => "red");
$result = array_diff_assoc($array2, $array1);
if (!count($result)) echo "array2 is contained in array";

答案 1 :(得分:1)

怎么样......

$intersect = array_intersect_assoc($a, $b);
if( count($intersect) == count($b) ){
    echo "yes, it's inside";
}
else{
    echo "no, it's not.";
}
  
    

array_intersect_assoc     array_intersect_assoc()返回一个数组,其中包含所有参数中存在的array1的所有值。

  

答案 2 :(得分:0)

function checkSameValues($a, $b){
   if ( in_array($a,$b) ) return true;
   else return false;
}

答案 3 :(得分:0)

这显然只检查depth = 1,但很容易适应递归:

// check if $a2 is contained in $a1
function checkSameValues($a1, $a2)
{
    foreach($a1 as $element)
    {
        if($element == $a2) return true;
    }
    return false;
}

$a1 = array('foo' => 'bar', 'bar' => 'baz');
$a2 = array('el' => 'one', 'another' => $a1);

var_dump(checkSameValues($a2, $a1)); // true
相关问题