[英]Compare two arrays of objects by specific object key value
這可能真的很簡單,但我似乎無法理解。 我有兩個對象$a
和$b
數組。 在$a
我有帶有關鍵email
對象,在$b
我有帶有user_email
對象(由於來自API,因此無法更改)。 我想要作為輸出的第三個數組$c
具有所有對象,其中email == user_email
。 我試過像這樣使用array_udiff
:
$c = array_udiff($a, $b,
function ($obj_a, $obj_b) {
return $obj_a->email - $obj_b->user_email;
}
);
由於某些原因,$ obj_b並不總是像我想的那樣來自數組$b
的對象。 有沒有干凈的解決方案? 謝謝。
您可能正在尋找array_uintersect 。 另外,您應該將字符串與strcmp進行比較,甚至與strcasecmp進行比較 。 請記住,PHP將數組元素傳遞給回調的順序並不總是與數組的順序相同。
$a = [(object)['email' => 'a'], (object)['email' => 'b'], (object)['email' => 'c']];
$b = [(object)['user_email' => 'c'], (object)['user_email' => 'a'], (object)['user_email' => 'd']];
$comparer = function($obj_a, $obj_b) {
$email_a = property_exists($obj_a, 'email')
? $obj_a->email
: $obj_a->user_email;
$email_b = property_exists($obj_b, 'email')
? $obj_b->email
: $obj_b->user_email;
return strcasecmp($email_a, $email_b);
};
// only objects with email property
$c = array_uintersect($a, $b, $comparer);
// both objects with email and user_email property
$d = array_merge(
array_uintersect($a, $b, $comparer),
array_uintersect($b, $a, $comparer)
);
如果參數是具體類,則可以將使用property_exists
進行的測試更改為使用instanceof
進行的測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.