I have a huge collection of data (array items). Each item within should be distinguished as dupe if all values for given keys are the same. Imagine this as a unique composite key.
$recordsAll = [
['unique1' => 'foo', 'unique2' => 'bar', 'whatever1' => 'whatever1'], // 1st OK
['unique1' => 'baz', 'unique2' => 'zaz', 'whatever2' => 'whatever2'], // 2nd OK
['unique1' => 'foo', 'unique2' => 'kkk', 'whatever3' => 'whatever3'], // 3rd OK (because unique2 is kkk not bar)
['unique1' => 'baz', 'unique2' => 'zaz', 'whatever4' => 'whatever4'], // 4th DUPE (dupe of the 2nd because on both unique1 is bar and unique2 is zaz)
];
In the example above the unique composite key is a combination of unique
and unique2
.
I'm able to remove the dupes. I do it like that:
$recordsAll = collect($recordsAll);
$recordsCleaned = $recordsAll->unique(function ($item) {
return $item['unique1'].$item['unique2'];
});
I'm able to confirm that it works by counting results in both. Collection with everything should give me obviously 4
, while the cleaned one should give me 3
, and they do…
dd($recordsAll->count(), $recordsCleaned->count()); // prints 4 and 3
What I don't know how to do (or at least I have an idea but it does not work) is to store the duped record(s) in another array (collection). So I don't want to only remove the dupes and use cleaned collection. Later I also want to perform some logic on the collection containing dupes.
I thought that a simple diff
will do the job for me, since the documentation is quite clear.
The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection:
$dupes = $recordsAll->diff($recordsCleaned);
$dupes->all();
However this does not work. I tried as well with diffAssoc
and diffKeys
. Please help me, how I can have the 4th (duped) item and all next dupes in a brand new collection?
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2r9FJfz
via IFTTT
Aucun commentaire:
Enregistrer un commentaire