比较两个PHP对象-PHP和对象 [英] Comparing two PHP objects - PHP and OBJECTS

查看:77
本文介绍了比较两个PHP对象-PHP和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的对象.

$ 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] => 
)

$ 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] => 
) 

我需要比较这个对象并仅获得这两个对象的差异.

I need to compare this object and get the difference in these two objects only.

我检查了以下链接,但没有用.

I have checked the below links but no use.

比较两个stdClass对象

比较2个对象PHP

我的示例代码如下

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; 
}

有人可以帮助我提供代码吗?

Can someone help me with the code.

推荐答案

使用 array_diff_assoc() ;例如:

Use array_diff_assoc(); e.g:

<?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);

array_diff_assoc 执行带有附加索引检查的数组差异.在您的情况下,这是必需的,因为您要执行键/值差异,而不是仅对值进行差异.

array_diff_assoc performs a diff of arrays with additional index check. In your case this is required because you want to perform a key/value diff, not a diff on the values alone.

上面的代码产生:

Array
(
    [BellId] => 1
    [BellDescription] => foo
)

注意:您可以将 stdClass()的实例透明地转换为 array ,反之亦然:

Note: you can transparently cast an instance of stdClass() to an array and vice versa:

$arr = ['id' => 1];
$obj = (object) $arr;
$arr = (array) $obj;

// etc. 

希望这会有所帮助:)

这篇关于比较两个PHP对象-PHP和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆