2

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

1

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.

0

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;
                   endif;
               endforeach;
        endforeach;
enforeach;

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 that you have read and understand our privacy policy and code of conduct.

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