4

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?

john 1991
  • 26
  • 2
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • Related to http://stackoverflow.com/questions/16590174/convert-zend-db-resultset-hydratingresultset-to-array-of-objects/16692849 – Karl Lorey Nov 17 '13 at 15:35

2 Answers2

6

As pointed out by Steve, you can iterate the result set like an array. But if you need it as an actual array, ZF2 provides as iteratorToArray function that will convert it to an array for you.

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

    return \Zend\Stdlib\ArrayUtils::iteratorToArray($results);
}
limos
  • 1,526
  • 12
  • 13
  • This is what I was looking for here: http://stackoverflow.com/questions/16590174/convert-zend-db-resultset-hydratingresultset-to-array-of-objects/16692849 If you post your answer there, I will accept it! Thanks a lot! – Karl Lorey Nov 17 '13 at 15:34
  • 4
    Seems like the second paramater $recursive should be false. – Karl Lorey Nov 17 '13 at 16:06
4

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;
}
  • 6
    i'm looking to get an array of objects, not an array of arrays, for consistency sake – Patrioticcow Sep 22 '13 at 17:39
  • 4
    The `HydratingResultSet` implements the `Iterator` interface so you can already use `foreach` to loop over the results as if it were an array. If you really do need an array of objects you will have to manually construct the array using such a `foreach`. – Steve Jordan Sep 23 '13 at 11:21