Compare ArrayCollection with array of objects

2019-07-18 15:56发布

I have a StatColle entity in a ManyToMany relationship with a Groupe entity. I want to compare an array of Groupe objects with an arrayCollection.

Here's my code :

//Create array of Groupe objects
$nameOfSelectedGroupes = $request->request->get('selectedGroupes');

        $groupes= [];
        foreach ($nameOfSelectedGroupes as $nameOfSelectedGroupe) {
            $groupe = $em->getRepository(Groupe::class)->findBy(['nom' => $nameOfSelectedGroupe]);
            $groupes[] = $groupe;
        }

// Compare array of objects with ArrayCollection of objects
...request to get StatColle...
foreach ($resultats as $resultat)
    {
        if ($groupes == $resultat->getGroupes()->toArray())
        return $resultat;
    }
...

This is always returning null. I think that $resultat->getGroupes()->toArray() is not the correct way to get Groupes linked to StatColle entity.

Do you have an idea to compare these arrays ?

1条回答
Animai°情兽
2楼-- · 2019-07-18 16:06

I think you can't compare arrays like that. Try array_diff, and then check if the resultant array is empty (means they are the same):

foreach ($resultats as $resultat){
    $compare = array_diff($groupes, $resultat->getGroupes()->toArray());
    if (empty($compare)){
        return $resultat;
    }
}

I think that should work.

查看更多
登录 后发表回答