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?
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
...
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With