Search code examples
phparraysobjectzend-framework2zend-db

how to return an array of objects in zend framework 2?


I am doing a query in zf2 and i get back a object(Zend\Db\ResultSet\HydratingResultSet) that i have to a foreach on, in order to get to the properties.

I would like to get an array of objects by default.

here is some code i have:

factory

'address-mapper'  => function ($serviceManager) {
    $mapper = new Mapper\Address();
    $mapper->setDbAdapter($serviceManager->get('Zend\Db\Adapter\Adapter'));
    $mapper->setEntityPrototype(new Entity\Address);
    $mapper->setHydrator(new \Zend\Stdlib\Hydrator\ClassMethods);

    return $mapper;
}

the query

public function fetchById()
{
    $select = $this->getSelect()->where(array('id' => $Id));
    return $this->select($select);
}

this gives me back:

object(Zend\Db\ResultSet\HydratingResultSet)[459]
      protected 'hydrator' => 
        object(Zend\Stdlib\Hydrator\ClassMethods)[415]
          protected 'underscoreSeparatedKeys' => boolean true
          private 'callableMethodFilter' => 
          ....
          ....

any ideas what i need to do?


Solution

  • The Zend\Db\ResultSet\HydratingResultSet has a toArray method. So you can do this to get a multi-dimension array of the results instead of a result set:

    public function fetchById()
    {
        $select = $this->getSelect()->where(array('id' => $Id));
        $arrayResults = $this->select($select)->toArray()
        return $arrayResults;
    }