Diff object collections in PHP

I often come across a scenario where I have two collections of objects (either an array or the IteratorAggregate class), and I need to distinguish between the two lists.

Through diff, I mean:

  • Detecting duplicate objects (duplicate detection logic will vary depending on the case)
  • Add new objects
  • Delete objects that are not in another list

Essentially, I'm looking for something like array_diffthat works with objects. So far, I have been repeating the same logic over and over for each type of collection. Obviously, since the conditions for repeating objects will differ from case to case, there is no particular solution. But is there a general outline or abstraction that people find an elegant way to handle this?

+3
source share
2 answers

spl_object_hash helps you determine if two objects match.

+2
source

Since PHP5.2 there is a native collection of objects with SplObjectStorage :

The SplObjectStorage class provides a map from objects to data or, ignoring data, a set of objects. This dual purpose can be useful in many cases with the need for unique identification of objects.

Example

$obj1 = new StdClass; $obj1->prop = 1;
$obj2 = new StdClass; $obj2->prop = 2;
$obj3 = new StdClass; $obj3->prop = 3;
$obj4 = new StdClass; $obj4->prop = 4;
$obj5 = new StdClass; $obj5->prop = 5;

$collection1 = new SplObjectStorage;
$collection1->attach($obj1);
$collection1->attach($obj2);
$collection1->attach($obj3);

$collection2 = new SplObjectStorage;
$collection2->attach($obj3);
$collection2->attach($obj4);
$collection2->attach($obj5);   

SplObjectStorage , , , Serializable ArrayAccess ( 5.3), , Traversable. SplObjectStorage, . :

function collection_diff(SplObjectStorage $c1, SplObjectStorage $c2)
{
    $diff = new SplObjectStorage;
    foreach($c1 as $o) {
        if(!$c2->contains($o)) {
            $diff->attach($o);
        }
    }
    return $diff;
}

, , . :

$diff = collection_diff($collection1, $collection2);
var_dump( $diff ); // will contain $obj1 and $obj2

:

+1

Source: https://habr.com/ru/post/1753582/


All Articles