Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
up vote 2 down vote accepted

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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