\$\begingroup\$
\$\endgroup\$
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:
$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?
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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
)
answered Sep 6, 2011 at 14:33
-
\$\begingroup\$ Thanks for this. Is the function id() necessary? I don't see it being used. \$\endgroup\$JordanC– JordanC2011年09月12日 22:08:18 +00:00Commented Sep 12, 2011 at 22:08
-
1\$\begingroup\$ It is used as the first argument to array_map (the first argument is a string that is the name of a function to use). \$\endgroup\$kasterma– kasterma2011年09月13日 01:23:05 +00:00Commented Sep 13, 2011 at 1:23
lang-php