检查对象数组是否包含第二个对象数组

时间:2014-05-09 13:24:17

标签: php dom-node

我需要检查一个DOMNode对象数组是否包含类似DOMNode个对象数组中的所有项目。

通常,为了检查数组是否包含另一个数组,我尝试了this question中概述的一些方法。但是,array_intersect()array_diff()都会比较基础(string) $elem1 === (string) $elem2上的数组项 - 这会导致DOMElements出现以下错误,因为它们无法转换为字符串。

PHP Catchable fatal error: 
Object of class DOMElement could not be converted to string in...

处理此问题的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

我已经做了这个似乎有效,例如我用各种对象和类型填充两个数组只是为了看它是否有效:

$array = array(new DOMDocument(), 'foobar', 112312, new DateTime('Y'));
$array2 = array(new DOMDocument(), 'foobar',12312, false, new DateTime('Y'), 112312, true);

var_dump(array_diff_two($array,$array2)); //returns true

$array = array(new DOMDocument(), 'foobar', 112312, new DateTime('m'));
$array2 = array(new DOMDocument(), 'lorem ipsum!',12312, false, new DateTime('Y'), 112312, true);

var_dump(array_diff_two($array,$array2)); //returns false

function array_diff_two($array1, $array2){
    // serialize all values from array 2 which we will check if they contain values from array 1
    $serialized2 = array();
    foreach ($array2 as $value){
        $serialized2[] = serialize($value);
    }

    // Check if all values from array 1 are in 2, return false if it's not found
    foreach ($array1 as $value) {
        if (! in_array(serialize($value), $serialized2)) {
            return false;
        }
    }
    return true;
}

答案 1 :(得分:1)

正如我现在所写,这是另一种解决方案。在我看来,Tim's solution更具可读性。

//Does array of DOMNodes contain other array DOMNodes
private function array_contains_array($haystack,$needle){
    //Create object hash array of $haystack
    $haystackHashArr = array();
    foreach ($haystack as $idx => $haystackObj) {
        $haystackHashArr[$idx] = spl_object_hash($haystackObj);
    }

    //Now search for hashes of needle array objects in Haystack-hash-Array
    foreach ($needle as $domNode) {
        $huntedForHash = spl_object_hash($domNode);
        foreach($haystackHashArr as $hsHash){
            if ($hsHash == $huntedForHash) continue 2;
        }
        //Only get here if an item not found (Due to continue statement)
        return false;
    }
    return true;
}