我有兩個相似的對象: 對象老:獲取類似對象之間的鍵和值的區別在PHP
object(Party)#203 (16) {
["connection":protected]=>
object(Connection)#202 (6) {
["token":"Connection":private]=>
string(64) "xyzxxyzxyz"
["url":"Connection":private]=>
string(33) "https://api.test.com"
["singularAction"]=>
string(5) "party"
["pluralAction"]=>
string(7) "parties"
["action"]=>
string(5) "party"
}
["emailAddresses"]=>
array(3) {
[0]=>
array(3) {
["id"]=>
int(273530863)
["type"]=>
NULL
["address"]=>
string(19) "[email protected]"
}
[1]=>
array(3) {
["id"]=>
int(274183291)
["type"]=>
NULL
["address"]=>
string(18) "[email protected]"
}
[2]=>
array(3) {
["id"]=>
int(278650133)
["type"]=>
NULL
["address"]=>
string(26) "[email protected]"
}
}
}
和對象的更新:
object(Party)#201 (16) {
["connection":protected]=>
object(Connection)#202 (6) {
["token":"Connection":private]=>
string(64) "xyzxxyzxyz"
["url":"Connection":private]=>
string(33) "https://api.test.com"
["singularAction"]=>
string(5) "party"
["pluralAction"]=>
string(7) "parties"
["action"]=>
string(5) "party"
}
["emailAddresses"]=>
array(4) {
[0]=>
array(3) {
["id"]=>
int(273530863)
["type"]=>
NULL
["address"]=>
string(19) "[email protected]"
}
[1]=>
array(3) {
["id"]=>
int(274183291)
["type"]=>
NULL
["address"]=>
string(18) "[email protected]"
}
[2]=>
array(3) {
["id"]=>
int(278650133)
["type"]=>
NULL
["address"]=>
string(26) "[email protected]"
}
[3]=>
array(1) {
["address"]=>
string(27) "[email protected]"
}
}
}
視覺上的差異是最後的電子郵件地址作爲更新對象中的最後一個條目出現。我如何突出顯示PHP的差異並抓住它? 我想檢查兩個對象的每個條目,找出關鍵和值的差異,並用它做一些事情。
我已經成功地寫是這樣的:
//Get the updated object....
$newObject = $this;
//Now get the object before update was executed...
$oldObj = $this->oldObject;
//Remove object memebers from the new object for easy comparison with the old...
unset($newObject->oldObject, $newObject->about, $newObject->createdAt, $newObject->updatedAt, $newObject->lastContactedAt, $newObject->pictureURL);
//Remove object memebers from the old object....
unset($oldObj->about, $oldObj->createdAt, $oldObj->updatedAt, $oldObj->lastContactedAt, $oldObj->pictureURL);
$varsNewObj = get_object_vars($newObject);
$varsOldObj = get_object_vars($oldObj);
//Remove further unneeded memebers....
unset($varsNewObj['connection']);
unset($varsOldObj['connection']);
$arrayData = [];
foreach ($varsNewObj as $values) {
if (is_string($values) && $values != null) {
var_dump('New Values: ' . $values);
}
if (is_array($values)) {
foreach ($values as $value) {
if (is_string($value) && $value != null) {
//var_dump($value);
}
if (is_array($value)) {
foreach ($value as $v) {
if ($v != null) {
//var_dump($v);
}
}
}
}
}
}
什麼上面的代碼所做的是讓每一個需要來自新對象比較字符串。同樣的原則可以應用於$ oldObj,但是我對後來如何做比較感到困惑,因爲我腦海中似乎並不奏效。
你可以用'get_object_vars'([手動鏈接](http://php.net/manual/function.get-object-vars.php))開始並比較它們。它是否必須遞歸? – Kaddath
不幸的是。 –
以及我沒有時間爲你編寫它(而不是網站的目的),但我寫了類似的JavaScript遞歸函數(實際上是爲了找到對象結構中的特定鍵),如果你感興趣可以激勵你 – Kaddath