3
\$\begingroup\$

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?

asked Sep 6, 2011 at 5:27
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for this. Is the function id() necessary? I don't see it being used. \$\endgroup\$ Commented 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\$ Commented Sep 13, 2011 at 1:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.