Flatten Array Result of Symfony Doctrine Array Result Flatten Array Result of Symfony Doctrine Array Result symfony symfony

Flatten Array Result of Symfony Doctrine Array Result


Once you get the array of identifiers [0 => ['id' => 1], 1 => ['id' => 6], 2 => ['id' => 26] ...] just you have to use array_column function to get the values from a single column in the input array:

$ids = array_column($result, 'id');

Since PHP 5.5.0

Output:

Array(    [0] => 1    [1] => 6    [2] => 23    ...)


The result you are getting:

array(  0 => object of type entity,  1 => another object of type entity,  2 => another object of type entity,)

Is probably a result of findBy() or getResult() methods. To achieve what you want you will need to create your own query and do something like this:

$result = $entityManager->createQueryBuilder()    ->from('AcmeDemoBundle:Entity', 'e') //your entity    ->select('e.id') //your id field    ->getQuery()    ->getScalarResult();

This will give you array you're expecting


The best practices are to use the symfony native method, so as Tomasz Madeyski says, Use

...->getQuery()->getScalarResult()

You can also get it that way by doing

->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)

A good practice also is to create the method INTO the repository class and make it hybrid by giving the choice of the two types, for exemple :.

public function findAll($hydratedArray = false){    $query = $this  ->createQueryBuilder('p')                    ->leftJoin('p.company', 'c')                    ->select('p')                    ->orderBy('c.name', 'ASC');    $result = $hydratedArray    ? $query                                    ->leftJoin('p.series', 's')                                    ->leftJoin('s.variety', 'v')                                    ->addSelect('c', 's', 'v')                                    ->getQuery()                                    ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY) // or getScalarResult()                              : $query->getQuery()->getResult();    return $result;}