How to get category ids from product collection

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);

If you want to get all category ids based on the array of your product ids. You can get it as following way

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productIdsArray = array(1,2,3,4,5,6,7,8,9); // your product ids
$products = $objectManager->create("Magento\Catalog\Model\Product")->getCollection()->addAttributeToFilter('entity_id',array('in'=> $productIdsArray));

$allCategories = array();  // create a blank array
foreach ($products as $product) {
    $allCategories = array_merge($allCategories, $product->getCategoryIds());  // Merge product category ids array with $allCategories
}
$finalArray = array_unique($allCategories); // removes duplicate entries from an array

Note: Do not use ObjectManger directly in your phtml file. I recommend to use dependency injection.


You can always get the assigned categories of a product using following code.

In Constructor:

public function __construct(
        ...
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        ...
        $this->_productFactory = $productFactory;
        ...
    }

And in your method use following code

$product = $this->_productFactory->create()->load($pid); // $pid = Product_ID

$cats = $product->getCategoryIds(); // All Categories of $product you will get in array format eg. array(catid 1, catid 2, catid 3)