Magento 2 convert an array to a collection object

Integrate Magepack with Magento/Adobe commerce

Today we will let you know How to convert an array to a collection object in Magento

For example, we have an array of data fetched from the database.
And we want to merge it with the Magento collection object or want to provide the data as the collection

The collection class is Magento\Framework\Data\Collection, but you need to instantiate it using the autogenerated factory Magento\Framework\Data\CollectionFactory. Obtain it using the object manager or – preferred – by adding it as a constructor parameter to the class where you use it

Try below code to Convert an array to a collection in magento2

$dataArray = [];
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $objectManager->create('Magento\Framework\Data\Collection');

foreach ($dataArray as $key => $row) {
$varienObject = new \Magento\Framework\DataObject();
$varienObject->setData($row);
$collection->addItem($varienObject);
}
return $collection;

Related post Check current page action in magento2

Like us on Facebook and Linkedin for more updates.

Back To Top