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\$

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

Your Answer

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

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