3

I am not looking for $myRowset->toArray(); because I want to get an array of objects.

What I want to do is to be able to merge $myRowset with an array of objects.

$myOtherArray = [new Foo(), new Bar()];
$array = array_merge($myRowset, $myOtherArray);

With a Zend_Db_Table_Rowset, it is impossible. Using $myRowset->toArray(); doesn't work too because I need an array of objects.

Edit - Example of code doing what I want, but I'm looking for a better solution if it exists:

// Convert the Zend_Db_Table_Rowset to an array of Zend_Db_Table_Row
$myRowset = $dbTable->fetchAll();
$rowArray = array();
foreach ($myRowset as $row) {
    $rowArray[] = $row;
}

// Merge with other array of objects
$myOtherArray = [new Foo(), new Bar()];

$finalArray = array_merge($rowArray, $myOtherArray);
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • I'm not sure how Zend is supposed to know what object you want to instantiate from the data returned from the database. Other than foreaching over the array and instantiating each object yourself, I don't think what you want is possible, unless by object you just mean stdClass objects which you can make by casting an array to object. But you really don't want to do that, for a lot of reasons. – GordonM Jun 24 '12 at 18:37
  • @GordonM No need for instanciating anything, the rowset returned by the query contains subtypes of `Zend_Db_Table_Row` (my model objects). See my edit for better understanding. – Matthieu Napoli Jun 24 '12 at 18:51
  • I think the solution you have already is pretty much your only option. You could extend Zend_Db_Table_Rowset with a method to return the array of rows to make it easier to manage but that's about it. – GordonM Jun 24 '12 at 18:57
  • Why not use the zend fetch mode? https://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.select.fetch-mode if you were to do `$db->setFetchMode(Zend_Db::FETCH_OBJ);` then any `fetchAll()` statement after that will return an array of objects... – Krzysztof Karski Aug 29 '16 at 07:43

2 Answers2

3

Here is my "cleanest" solution: I override Zend_Db_Table_Rowset

class My_RowSet extends Zend_Db_Table_Rowset {

    public function rowArray() {
        $rowArray = array();
        foreach ($this as $row) {
            $rowArray[] = $row;
        }
        return $rowArray;
    }

}

and Zend_Db_Table:

abstract class My_Db_Table extends Zend_Db_Table {

    protected $_rowsetClass = 'My_RowSet';

}

Now I can do:

$myRowset = $dbTable->fetchAll();
$rowArray = $myRowset->rowArray();
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
1

You can use

/** @var Zend_Db_Table_Row[] $rows */
$rows = iterator_to_array($rowset)
Tomáš Fejfar
  • 11,129
  • 8
  • 54
  • 82