Hi,
I have 2 (or more) Collections
. How do I filter only unique id
and merge them into 1 collection ? I don’t want to create an array, and then work on the array then collection again. I like the functions that collection has.
$issue1 = (new Collection($this->Users->find('filterPassport')->all()));
$issue2 = (new Collection($this->Users->find('filterPermit')->all()));
// Merge 2 collections. Maybe like :
$issue1->mergeUnique($issue2);
Did you try asking chatgpt or grok? They usually can give quite good answers for such clear questions and issues.
Thanks. Chatgpt gave the correct answer after a few tries. I prefer to ask it here, because of the quality of answers. Here is what chatgpt finally gave which is correct
$merged = (new Collection($issue1))
->append($issue2)
->groupBy('id')
->map(fn($items) => $items[0]);
$final = new Collection($merged->toList()); // Reindex and wrap into a Collection
Hah, good, glad you got the answer.
Yeah, this happen sometimes, but at least there is a solution somewhere around the corner then.
I see what you mean
It gives first
$merged = $issue1
->append($issue2) // or ->appendIterator($issue2)
->unique('id'); // Ensure uniqueness by 'id'
as possible solution, which then probably wouldn’t work 