1

enter image description hereSame with here : Magento 1: $productCollection->getData() vs foreach ($productCollection as $product), want add more information. Create new product then

$productCollection = $objectManager->get('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create()->setStoreId('0')
->addAttributeToFilter('entity_id', '1638763');

Now

var_dump($productCollection->getData());  // return the item
foreach ($productCollection as $key => $item) {
    var_dump($key);
}. // nothing in here 

And try

productCollection->load();

Both method return null, Why I can't get the item after load() or using foreach function?

1

Try to use below in foreach loop.

First get the data in some variable and loop through that variable

$proData = $productCollection->getData();
foreach ($proData as $key => $item) {
    var_dump($key);
    var_dump($item);
    var_dump($item['entity_id']);
} // data will be display
3
  • Yes, that works, but question is why I can't foreach productCollection? When using foreach directly why it is empty. – Kai Jun 30 '20 at 1:19
  • you have to use $productCollection->getData() and print out some var_dump($item) instead of just $key – sandip Jun 30 '20 at 1:23
  • Why have to use getData() ? What's the difference for using foreach directly and getData then foreach() ? I see magento using foreach without getData() lots of place. Example : vender/magento/module-visual-merchandiser/Model/Rules $positions = $this->getProductsPositions($collection, $ids); – Kai Jun 30 '20 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.