PHP get difference of two arrays of objects

Viewed 43815

I know there is array_diff and array_udiff for comparing the difference between two arrays, but how would I do it with two arrays of objects?

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

My arrays are like this one, I am interested to see the difference of two arrays based on IDs.

4 Answers

Here is my take on this

/**
     * 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;
    }
Related