比较对象属性并在PHP中显示差异 [英] 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 ?!
推荐答案
类似于下面的过程,它迭代并进行递归比较是数组中的项本身就是数组可以工作:
Something like the following, which iterates through and does a recursive diff is the item in the array is itself an array could work:
与array_diff的工作类似,但是会检查它是否首先是一个数组(is_array),如果是,则将该键的diff设置为该数组的diff.递归地重复.
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;
}
它的工作原理如下:
$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
)
)
*/
这篇关于比较对象属性并在PHP中显示差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!