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?

1

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is what I was looking for here: stackoverflow.com/questions/16590174/… If you post your answer there, I will accept it! Thanks a lot!
Seems like the second paramater $recursive should be false.
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;
}

2 Comments

i'm looking to get an array of objects, not an array of arrays, for consistency sake
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.