我有两个这样的对象。
$array1
stdClass Object (
[BellId] => 2
[BellCode] => BP001
[BellDescription] => SPI SPEED ABNORMAL,CHK BELT
[ControllerId] => 3
[CreatedBy] => 1
[CreatedOn] => 2016-08-19 15:09:25
[ModifiedBy] =>
[ModifiedOn] =>
)
Run Code Online (Sandbox Code Playgroud)
$array2
stdClass Object (
[BellId] => 1
[BellCode] => BP002
[BellDescription] => MCB TRIPPED,CHK MTR SHORT,O/L.
[ControllerId] => 3
[CreatedBy] => 1
[CreatedOn] => 2016-08-19 15:09:25
[ModifiedBy] =>
[ModifiedOn] =>
)
Run Code Online (Sandbox Code Playgroud)
我只需要比较这个对象并获得这两个对象的差异。
我检查了以下链接,但没有用。
我的示例代码如下
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;
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我写代码吗?
使用array_diff_assoc(); 例如:
<?php
$foo = new stdClass();
$foo->BellId = 1;
$foo->BellDescription = 'foo';
$foo->CreatedBy = 1;
$bar = new stdClass();
$bar->BellId = 2;
$bar->BellDescription = 'bar';
$bar->CreatedBy = 1;
$diff = array_diff_assoc((array) $foo, (array) $bar);
print_r($diff);
Run Code Online (Sandbox Code Playgroud)
array_diff_assoc执行带有额外索引检查的数组差异。在您的情况下,这是必需的,因为您要执行键/值差异,而不是仅对值进行差异。
上面的代码产生:
Array
(
[BellId] => 1
[BellDescription] => foo
)
Run Code Online (Sandbox Code Playgroud)
注意:您可以透明地将 的实例转换stdClass()为 an array,反之亦然:
$arr = ['id' => 1];
$obj = (object) $arr;
$arr = (array) $obj;
// etc.
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
2605 次 |
| 最近记录: |