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.

2 Answers 2


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:

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

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.


You'll need a custom loop. I don't know the exact functions, but it would be something like this:

$categories = getCategories($productId);
$listOfCategores = array();
foreach ($categories as $cat):
    $all = getAllProductBelongTo($cat);
       foreach ($allProducts as $product)
            $categories = getCategories($product);
               foreach($categories as $ca)
                   if (!in_array($listOfCategories, $ca):
                      $listOfCategories .= $ca;

Now, $listOfCategories should be an array of all categories you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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