If you are creating a product import script for Magento, you probably need to generate on the fly all your category ids based on category names.
Here is a situation where you can use this script.
Your product feed contains a column called CATEGORY with values in this format: Girls>Infant>Basketball and Boys>Infant>Basketball
If you want to assign products from those categories to your Magento categories Girls > Infant > Basketball and Boys > Infant > Basketball , then you have to get the category ids for Girls, boys, Infant and Basketball. Remember that Infant id for Boys is not the same as Girls.
<?php function listArrayRecursive($someArray,$root) { $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $k => $v) { if ($iterator->hasChildren()) { } else { for ($cat_ids = array(),$cats = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { if($i%2){ $cat_ids[] = $iterator->getSubIterator($i)->key(); } else { $cats[] = $iterator->getSubIterator($i)->key(); } } $category_ids = implode(',', $cat_ids); $category_names = implode(',', $cats); $output[ $category_names ] = $root.','.$category_ids; } } return $output; } function nodeToArray(Varien_Data_Tree_Node $node) { $result = array(); if( is_object($node)) { $name = $node->getName(); $result[$name] = $name; $result[$name] = array(); if($node->hasChildren()){ foreach ($node->getChildren() as $child) { $result[$name][$child->getId()] = nodeToArray($child); } } else { $result[$name] = $name; } } return $result; } function load_tree($parentId,$store) { $tree = Mage::getResourceSingleton('catalog/category_tree')->load(); $root = $tree->getNodeById($parentId); if($root && $root->getId() == 1) { $root->setName(Mage::helper('catalog')->__('Root')); } $collection = Mage::getModel('catalog/category')->getCollection()->setStoreId($store)->addAttributeToSelect('name')->addAttributeToSelect('is_active'); $tree->addCollectionData($collection, true); return nodeToArray($root); }