How to convert an array to a collection object in Magento?


Suppose say we have an array of data fetched from the database.
And we want to merge it with Magento collection object or want to provide the data as collection object to the view(template) file.


$resource		= Mage::getModel('core/resource');
$connection		= $resource->getConnection('core_read');
$sql			= "SELECT * FROM custom_table WHERE some_field = ?";
$rows			= $connection->fetchAll($sql, array($someFieldValue));//this row will return an array

$collection = new Varien_Data_Collection();
foreach($rows as $row){
	$rowObj = new Varien_Object();

//now you can get the data using collection way
foreach($collection as $_data){

In order to create a collection object
1> Create an instance of Varien_Data_Collection

$collection = new Varien_Data_Collection();

2> Create an instance of Varien_Object and set the array of data

$rowObj = new Varien_Object();

3> Finally add the Varien_Object to Collection instance


Now you can play with the magic getters and setters of the collection class.

In order to have depth knowledge on Magento Collection you can refer to the Alan Storm’s article:
Varien Data Collections

2 thoughts on “How to convert an array to a collection object in Magento?”

  1. Hi @MagePsycho,

    I played a bit with your code and it seems, that Varien_Db_Collection
    doesn’t exist in the latest versions of Magento …

    I changed Varien_Db_Collection with Varien_Data_Collection
    and it worked for me.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.