PHP获得两个对象数组的差异

时间:2011-06-24 18:27:43

标签: php arrays

我知道有array_diffarray_udiff用于比较两个数组之间的差异,但我如何使用两个对象数组呢?

array(4) {
    [0]=>
        object(stdClass)#32 (9) {
            ["id"]=>
            string(3) "205"
            ["day_id"]=>
            string(2) "12"
        }
}

我的数组就像这个,我有兴趣看到基于ID的两个数组的区别。

4 个答案:

答案 0 :(得分:62)

这正是array_udiff的用途。编写一个按照您希望的方式比较两个对象的函数,然后告诉array_udiff使用该函数。像这样:

function compare_objects($obj_a, $obj_b) {
  return $obj_a->id - $obj_b->id;
}

$diff = array_udiff($first_array, $second_array, 'compare_objects');

或者,如果你使用PHP> = 5.3,你可以使用anonymous function而不是声明一个函数:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return $obj_a->id - $obj_b->id;
  }
);

答案 1 :(得分:3)

如果您想根据对象实例运行差异,这是另一个选项。您可以将其用作array_udiff的回调:

function compare_objects($a, $b) {
    return strcmp(spl_object_hash($a), spl_object_hash($b));
}

如果你确定数组都只包含对象 - here's my personal use case,你只想使用它。

答案 2 :(得分:2)

如果你想比较字符串属性(例如名字),这是另一种选择:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return strcmp($obj_a->name, $obj_b->name);
  }
);

答案 3 :(得分:0)

这是我的看法

/**
     * Compare two objects (active record models) and return the difference. It wil skip ID from both objects as 
     * it will be obviously different
     * Note: make sure that the attributes of the first object are present in the second object, otherwise
     * this routine will give exception.
     * 
     * @param object $object1
     * @param object $object2
     * 
     * @return array difference array in key-value pair, empty array if there is no difference
     */
    public static function compareTwoObjects($object1, $object2)
    {
        $differences=[];
        foreach($object1->attributes as $key => $value) {
            if($key =='id'){
                continue;
            }
            if($object1->$key != $object2->$key){
                $differences[$key] = array(
                                            'old' => $object1->$key,
                                            'new' => $object2->$key
                                        );
            }
        }
        return $differences;
    }