0

I'm trying to get a product collection. I got it by function:

public function getProductCollection()
{
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(3);

    return $collection;
}

And my template file is:

$productCollection = $block->getProductCollection();
foreach($productCollection as $product) {
    echo $product->getData() . "<br />";
}

But I got an error Array to string conversion in this line:

echo $product->getData() . "<br />";

Could someone tell me why?

1

$product->getData() returns an array. you cannot echo an array.

Try with echo "<pre>"; print_r($product->getData()) or echo "<pre>"; var_dump($product->getData())

  • But why it displayed an arrays of products instead of a real products? – HELPME Aug 24 '18 at 12:10
  • not sure I understand your question. show an example of what you were expecting. – Marius Aug 24 '18 at 12:38
  • I was expecting that when I'll get a product collection, products (that I had imported manually in the admin panel) will be displayed. Instead, it displays five seperate product arrays, which is key => value pairs, not a real products (that I have imported. – HELPME Aug 24 '18 at 12:41
1

you need to store the $collection=$product->getData(); and then use foreach loop to get the content . actually mistake you did was trying to use echo function on $product->getData().

above function was returning and array and you were trying to print it .

echo functions generally fails in this situation . @marius suggested you correct function to get content of an array.

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.