Magento Categories – How to Get Magento Categories by Array of Category IDs

categorysubmenu

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();
} ?>

Best Answer

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.