简体   繁体   中英

How to get the difference between two arrays of objects

I have 2 array of objects, for example

$arr1 = [
  (new MyClass())->setId(1),
  (new MyClass())->setId(2),
  (new MyClass())->setId(3),
];

$arr2 = [
  (new MyClass())->setId(1),
  (new MyClass())->setId(2),
];

I'd need to find the difference between these 2 arrays, in this example I'd need to get an array with a single element, the one with id == 3.

I know I should use array_udiff (maybe) but I couldn't figure out how.

The following logic might help:

<?php
class MyClass
{
    public $id = null;

    public function setId($id) {
        $this->id = $id;
        return $this;
    }
}

$arr1 = [
    (new MyClass())->setId(1),
    (new MyClass())->setId(2),
    (new MyClass())->setId(3),
];

$arr2 = [
    (new MyClass())->setId(1),
    (new MyClass())->setId(2),
];

$difference = array_udiff($arr1, $arr2,
    function ($objOne, $objTwo) {
        return $objOne->id - $objTwo->id;
    }
);

Output:

Array
(
    [2] => MyClass Object
        (
            [id] => 3
        )

)

working demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM