PHP综合对象差异函数

时间:2015-01-06 04:39:25

标签: php object recursion comparison

有没有人知道一个php函数会接收两个对象并将一组完整的差异作为对象返回?

我将使用json编码数据作为我想要实现的目标的一个例子:

对象A:

{
    "Name":"Original",
    "Id": 5,
    "Data":{
        "Value1": 1,
        "Value2": [
            5, 7, 8, 10
        ],
        "Value3": {
            "Exists": true
        }
    }
}

对象B:

{
    "Name":"ThisNameChanged",
    "Id": 5,
    "Data":{
        "Value1": 7,
        "Value2": [
            5, 8, 9
        ],
        "Value3": {
            "Exists": true
        }
    }
}

会回来:

{
    "Name":"ThisNameChanged",
    "Data":{
        "Value2": {
            "1": 8,
            "2": 9
        }
    }
}

如果不存在这样的功能(我猜可能会这样),我怎么写一个函数来做这个?有人能提供一个例子,还是函数?

2 个答案:

答案 0 :(得分:1)

以下是您要求的一些简单的功能示例,

但它并不完美,只为你提供思考的食物:

function objDiff ($obj1, $obj2) {
        $diff=array();
    $obj1Arr = (array)$obj1;
    $obj2Arr = (array)$obj2;

    foreach ($obj1Arr as $key=>$val) {

        if (!(isset($obj2Arr[$key]) && $obj2Arr[$key]===$val  )) {
            if (gettype($val)=='object') {

                if (isset($obj2Arr[$key])) {
                    if (gettype($obj2Arr[$key])=='object') {
                        $subDiff = objDiff($val,$obj2Arr[$key]);
                        $diff[$key]=$subDiff;
                    } else {
                        $diff[$key]=array($val,$obj2Arr[$key]);
                    }
                } else {
                    $diff[$key]=array($val,$obj2Arr[$key]);
                }
            } else {
                $diff[$key]=array($val,(isset($obj2Arr[$key]))?$obj2Arr[$key]:null);
            }
        }
    }
    return $diff;
}

有这些数据:

$obj1 = new stdClass();
    $obj1->test1 = 1;
    $obj1->test2 = 2;
       $subObj = new stdClass();
    $subObj->test1 = 1;
    $subObj->test2 = 2;
    $obj1->test3 = $subObj;
        $obj2 = new stdClass();
    $obj2->test1 = 3;
    $obj2->test2 = 4;
    $subObj = new stdClass();
    $subObj->test1 = 3;
    $subObj->test2 = 2;
    $obj2->test3 = $subObj;

 print_r(objDiff($obj1,$obj2) );

它返回:

Array
(
    [test1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [test2] => Array
        (
            [0] => 2
            [1] => 4
        )

    [test3] => Array
        (
            [test1] => Array
                (
                    [0] => 1
                    [1] => 3
                )

        )

)

答案 1 :(得分:0)

感谢Kim Alexander,我能够编写完成我想要做的代码。

function objDiff($obj1, $obj2, $diff = null) {
    if (is_null($diff))
        $diff = new stdClass;

    $obj1Arr = (array)$obj1;
    $obj2Arr = (array)$obj2;

    foreach($obj1Arr as $key => $val) {
        if (isset($obj2Arr[$key]))
        {
            if ($obj2Arr[$key] != $val)
            {
                if (is_object($obj2Arr[$key]) && is_object($val))
                    $diff->$key = objDiff($val, $obj2Arr[$key]);
                else
                    $diff->$key = $obj2Arr[$key];
            }
        }
    }
    return $diff;
}