Search code examples
phpsymfonycollections

Merging many collections in a single one symfony


(using Symfony 3.4)

I am trying to create an array collection by merging (getting only the objects) multiple collections. Sounds weird, let me explain.

I take all the users from the db and for each one I want to add in a single array collection all his/her licenses. My code:

 $users = $this->userRepository->findAllUsers($params);

 $users->forAll(function (User $user) use (&$array) {
     $array = array_merge($array, $user->getLicenses());
 });

 $a = new ArrayCollection($array);

How should I resolve this?


Solution

  • You can merge collections like this (from How to merge two php Doctrine 2 ArrayCollection()):

    $collection3 = new ArrayCollection(
        array_merge($collection1->toArray(), $collection2->toArray())
    );
    

    So that can be applied to your case:

    $users = $this->userRepository->findAllUsers($params);
    $licensesArray = [];
    
    foreach ($user in $users) {
        $licensesArray = array_merge($licencesArray, $user->getLicenses()->toArray());
    });
    
    $licenses = new ArrayCollection($licensesArray);
    

    This can result in having same license entity in the resulting collection several times. If that is not wanted, you can write some custom filtering to the array - or just create a repository getter for getting the licenses based on the user ids / user search params...