How to build a hierarchical tree from get_categories
See this Stack Overflow question. In the answer Jan Fabry does it like this:
$categories = get_categories();
// First index all categories by parent id, for easy lookup later
$cats_by_parent = array();
foreach ($categories as $cat)
{
$parent_id = $cat->category_parent;
if (!array_key_exists($parent_id, $cats_by_parent))
{
$cats_by_parent[$parent_id] = array();
}
$cats_by_parent[$parent_id][] = $cat;
}
// Then build a hierarchical tree
$cat_tree = array();
function add_cats_to_bag(&$child_bag, &$children)
{
global $cats_by_parent;
foreach ($children as $child_cat)
{
$child_id = $child_cat->cat_ID;
if (array_key_exists($child_id, $cats_by_parent))
{
$child_cat->children = array();
add_cats_to_bag($child_cat->children, $cats_by_parent[$child_id]);
}
$child_bag[$child_id] = $child_cat;
}
}
add_cats_to_bag($cat_tree, $cats_by_parent[0]);