9

I'm simply trying to fetch all records in a given table by extending Zend AbstractTableGateway and making use of inherited select() function. this select() function returns type Zend ResultSet however I'm not able get an array of results using toArray().

I get the following message:

Rows as part of this DataSource, with type object cannot be cast to an array

Update

I worked it out

assuming you have extended AbstractTableGateway

$resultSet = $this->select();
foreach($resultSet as $row) { echo $row->yourProperty }
2
  • 1
    Zend_Db_Result is already having a toArray(). could you please paste your code for reference.framework.zend.com/apidoc/2.0/classes/… Commented Oct 6, 2012 at 7:54
  • 2
    FYI: if you are using a custom array object prototype in the result set, adding a toArray() method to your entity will fix this Commented Jan 30, 2013 at 15:43

4 Answers 4

6

You should use HydratingResultSet like this :

class MyClassTable extends AbstractTableGateway
{
    public function __construct(Adapter $adapter)
{
    $this->adapter = $adapter;
    $this->resultSetPrototype = new HydratingResultSet();
    $this->resultSetPrototype->setObjectPrototype(new MyClass());
    $this->initialize();
}

public function fetchAll()
{
    $resultSet = $this->select();
    return $resultSet;
}

public function fetchAllToArray()
{
    $aData = $this->fetchAll()->toArray();
    return $aData;
}
Sign up to request clarification or add additional context in comments.

Comments

4

You can also try this

$sql = new Sql($adapter);

$select = $sql->select();

$select->from('table');

$statement = $sql->prepareStatementForSqlObject($select); 

$results = $statement->execute();

$resultSet = new ResultSet();
$resultSet->initialize($results);

print_r($resultSet->toArray());

With Zend\Db\ResultSet\ResultSet;

Comments

3

Just try to use

(array)$resultSet

I've used this sometimes on ZF and works fine.

1 Comment

Awesome shortcut. This has saved me a ton of time.
2

Mine issue was as @Fatmuemoo noted.

If you register your custom object prototype, code eg.

$resultSetPrototype = new ResultSet($entityClassName, new $entityClassName);
$instance->setResultSetPrototype($resultSetPrototype);

you have to implement toArray() method in yout Entity class.

public function toArray()
{
    return get_object_vars($this);
}

Comments

Your Answer

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