Magento – Get all Categories of Products in Category – PHP

categorycategory-productsmagento-1PHP

What I am trying to do is to get all of the categories that belong to products in a given category. Given the brand category Nike, I want to display the categories that products in Nike also belong too. For instance, in the category Nike there are products that also belong to the categories: Shoes, Shirts, Shocks etc. I want to display a list of these categories.

I have seen many many ways to display the subcategories and subcategories of a parent category. But I am unsure of how to get the categories that each product belongs to for a given category.

Any help or guidance is appreciated.

Best Answer

If you have a ready collection of products, then you can get all the categories that include current products without any binding to the product ID:

 <?php
$cats = [];
/** @var Mage_Catalog_Model_Product $_product */
foreach ($_productCollection as $_product) {
    $curProductCats = $_product->getCategoryIds();
    if (empty($curProductCats) || !is_array($curProductCats)) {
        continue;
    }
    $cats += array_flip($curProductCats); // Use the category id as key & merge prev. result with current
}
var_dump($cats);
?>

This code will return you the array, where categories ID will be the keys. This is the easiest way. In addition, you can modify the code according to your requirements.

Note, that such a cycles can slow down page loading speed when you have a large database.

Related Topic