Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten Array Result of Symfony Doctrine Array Result

With a repository I got an array result (each array is an entity object) like this:

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

each object has some properties like id and name, etc. But I what I want is flatten the whole array only with the id of each object.

What I want is this (flatten the array only with ID's):

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

My solution:

$ids = array_map($transform = function($entity) {
    if ($entity instanceof Entity) {
       return $entity->getId();
    }
 }, $myGreatDbResult);

My solution is working but is there a better way to get this result?

like image 537
goldlife Avatar asked Sep 23 '16 12:09

goldlife


1 Answers

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
    ...
)
like image 106
yceruto Avatar answered Sep 16 '22 16:09

yceruto