Karim Mtl
Karim Mtl

Reputation: 1251

Retrieve keys of an array of objects

I have an object with 2 attributes: id and name (class name: MyObject):

class MyObject {
  public id;
  public name;
}

And I have an array "MyObjects" where each item is a MyObject instance.

I am looping through this array to display all the objects in one view (MVC Web Application).

In an other place (Outside of the view and the controller (Validation class)) I will need an array of just the ids of all objects. What I am doing now is just use a private method in the controller to loop through "MyObjects" again and put the ids in an array:

   private function getMyObjectsIds($myObjects) {
      $myObjectsIds = array();
      foreach ($myObjects as $myObject) {
         $myObjectsIds[] = $myObject->id;
      }

      return $myObjectsIds;
   }

My Question: Is there a better way to retrieve the ids of all the objects as an array? I do not feel like this is the job of the controller and I would prefer to not save MyObjects in a new attribute of the model to just use the same method from the model.

Thanks

Upvotes: 3

Views: 48

Answers (2)

Coloured Panda
Coloured Panda

Reputation: 3467

You can create your own "array" class where that logic is encapsulated.

For example:

class Collection
{
    public $items;

    public function __construct(array $items)
    {
        $this->items = $items;
    }

    public function lists($name)
    {
        return array_map(function ($item) use ($name) {
            return $item->{$name};
        }, $this->items);
    }

    // Other common methods
}

To get a list of ids.

$myObjects = new Collection([]);
$ids = $myObjects->lists('id');

This is not a full example, as you would also need to implement Serializable and Iterator interfaces so it behaves like an array.

Upvotes: 1

michail_w
michail_w

Reputation: 4481

I would use array_map for it:

$myObjectsIds = array_map(function($item) {
    return $item->id;
}, $myObjects);

http://php.net/manual/en/function.array-map.php

Upvotes: 3

Related Questions