`
天梯梦
  • 浏览: 13633466 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

magento 数组转object How to convert an array to a collection object in magento?

 
阅读更多

Scenario

Suppose say we have an array of data fetched from 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.


Solution

<?php
$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_Db_Collection();
foreach($rows as $row){
    $rowObj = new Varien_Object();
    $rowObj->setData($row);
    $collection->addItem($rowObj);
}
 
//now you can get the data using collection way
foreach($collection as $_data){
    print_r($_data->getData());
}
 

Notes:
In order to create a collection object


1> Create an instance of Varien_Db_Collection

$collection = new Varien_Db_Collection();
 

 

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

$rowObj = new Varien_Object();
$rowObj->setData($row);
 

3> Finally add the Varien_Object to Collection instance

$collection->addItem($rowObj);
 

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

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

 

 

来源: http://www.blog.magepsycho.com/how-to-convert-an-array-to-a-collection-object-in-magento/

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics