Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

compare object properties and show diff in PHP

I'm searching for a way to show me the different properties/values from given objects...

$obj1 = new StdClass; $obj1->prop = 1;
$obj2 = new StdClass; $obj2->prop = 2;

var_dump(array_diff((array)$obj1, (array)$obj2));
//output array(1) { ["prop"]=> int(1) }

This works very well as long the property is not a object or array.

$obj1 = new StdClass; $obj1->prop = array(1,2);
$obj2 = new StdClass; $obj2->prop = array(1,3); 

var_dump(array_diff((array)$obj1, (array)$obj2))
// Output array(0) { }
// Expected output - array { ["prop"]=> array { [1]=> int(2) } }

Is there a way to get rid of this, even when the property is another object ?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like the following, which iterates through and does a recursive diff is the item in the array is itself an array could work:

Des similar work to array_diff, but it does a check to see if it is an array first (is_array) and if so, sets the diff for that key to be the diff for that array. Repeats recursively.

function recursive_array_diff($a1, $a2) { 
    $r = array(); 
    foreach ($a1 as $k => $v) {
        if (array_key_exists($k, $a2)) { 
            if (is_array($v)) { 
                $rad = recursive_array_diff($v, $a2[$k]); 
                if (count($rad)) { $r[$k] = $rad; } 
            } else { 
                if ($v != $a2[$k]) { 
                    $r[$k] = $v; 
                }
            }
        } else { 
            $r[$k] = $v; 
        } 
    } 
    return $r; 
}

It then works like this:

$obj1 = new StdClass; $obj1->prop = array(1,2);
$obj2 = new StdClass; $obj2->prop = array(1,3);
print_r(recursive_array_diff((array)$obj1, (array)$obj2));

/* Output:
    Array
    (
        [prop] => Array
            (
                [1] => 2
            )
    )
*/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...