How to Get Category IDs from Product Collection in Magento 2

categorymagento2

I have an array of product ids now i want to get all categories where these products belongs in magento2.

For example

we have categories cat_1, cat_2 ,cat_3, cat_4, cat_5, cat_6, cat_7

product_id_1 exist in cat_1, cat_2

product_id_2 exist in cat_3, cat_4

product_id_3 exist in cat_1, cat_5

Now i want a collection of category having categories cat1, cat_2, cat_3, and cat_5

Best Answer

You can use array_merge to get all the ids from collection

$prodIds=$block->getProductCollection();
$catIds=[];         
foreach($prodIds as $pid){          

         $product = $this->_productloader->create()->load($pid);   
         $proCats = $product->getCategoryIds();    
         $catIds= array_merge($catIds, $pproCats);   
     }
$finalCat = array_unique($catIds);
Related Topic