principlephpMinor
Getting an array from one property of an associative array best practice
Viewed 0 times
arraypracticegettingpropertyonefromassociativebest
Problem
I have an array of objects eg.
[
array(
'id' => 1,
'name' => "simon"
),
...
]
and I need to get an array of IDs eg.
[1,2,3,4,5];
Currently I'm doing this:
Is there a best practice way of doing this?
[
array(
'id' => 1,
'name' => "simon"
),
...
]
and I need to get an array of IDs eg.
[1,2,3,4,5];
Currently I'm doing this:
$entities = $this->works_order_model->get_assigned_entities($id);
$employee_ids = array();
foreach ($entities as $entity) {
array_push($employee_ids, $entity->id);
}Is there a best practice way of doing this?
Solution
I think array_map is what you are looking for:
php > $aa = array (array ("id" => 1, "name" => 'what'), array('id' => 2));
php > function id($i) { return $i['id'];};
php > print_r(array_map ('id', $aa));
Array
(
[0] => 1
[1] => 2
)Code Snippets
php > $aa = array (array ("id" => 1, "name" => 'what'), array('id' => 2));
php > function id($i) { return $i['id'];};
php > print_r(array_map ('id', $aa));
Array
(
[0] => 1
[1] => 2
)Context
StackExchange Code Review Q#4610, answer score: 2
Revisions (0)
No revisions yet.