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?

\$\endgroup\$
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
)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks for this. Is the function id() necessary? I don't see it being used. \$\endgroup\$ – JordanC Sep 12 '11 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 Sep 13 '11 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.