1

I have a situation where i have an array of category ids (containing both parent and child categories). now i want to fetch all categories by ids in the array in parent child relation i.e. if the category is top level (parent) then print it else if the category is child first get and print its parent category and then print the child categories. Until now i can get all categories from the list but the condition i applied to check if the category has parent category remain always true as all main categories are child of the root (default) category

<?php if ($_categories->getParentId()>0) {
    $_categories= $_categories->getParentCategory();
} ?>
  • 1
    Instead of $_categories->getParentId()>0 try to check $_categories->getParentId() != 1 && $_categories->getParentId() != Mage::app()->getStore()->getRootCategoryId(). This should exclude the root of all roots (id 1) and the default root category of the store. – Marius Aug 6 '14 at 8:10
  • @Marius thanks your comment(answer) worked perfectly for me, will you please answer it so that i can accept it as answer? – Haris Aug 6 '14 at 11:41
  • Done. I've written the comment as an answer – Marius Aug 6 '14 at 12:35
1

Based on the comments....
Instead of $_categories->getParentId()>0 try to check

$_categories->getParentId() != 1 && $_categories->getParentId() != Mage::app()->getStore()->getRootCategoryId(). 

This should exclude the root of all roots (id 1) and the default root category of the store.

2
    $cats = Mage::getModel('catalog/category')->getCollection()->addAttributeToFilter('level', array('gteq' => 2));
    $final = array();
    foreach($cats as $cat)
    {
        if($cat->getLevel() > 2 && !$cat->hasChildren())
        {
            $final[$cat->getEntityId()] = implode(',', c_getAllCategories($cat));
        }
    }
    var_dump($final);  


    function c_getAllCategories($category,$cats = null)
    {
        if(!$cats)
            $cats = array($category->getEntityId());
        $category = $category->getParentCategory();
        $cats[]=$category->getEntityId();
        if($category && $category->getLevel()>=2)
        {
            $cats= c_getAllCategories($category,$cats);
        }
        return $cats;
    }

it will print out every categories and their children

  • +1 for your help but i didn't tried it as @Marius answer worked for me. – Haris Aug 6 '14 at 11:42
  • @user8009 you're welcome :) in that case, please accept his answer. – Julien Lachal Aug 6 '14 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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