Skip to content

Instantly share code, notes, and snippets.

@pospi
Last active December 22, 2015 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pospi/6457915 to your computer and use it in GitHub Desktop.
Save pospi/6457915 to your computer and use it in GitHub Desktop.
Wordpress helper method for efficiently organising a hierarchical taxonomy into a hierarchical data structure. Similar code could be used to organise any hierarchical dataset.
<?php
/**
* Recursively sort an array of taxonomy terms hierarchically. Child categories will be
* placed under a 'children' member of their parent term.
*
* @param Array $cats taxonomy term objects to sort
* @param Array $into result array to put them in
* @param integer $parentId the current parent ID to put them in
*/
function sortHierarchicalTaxonomy(Array $cats, Array &$into, $parentId = 0)
{
foreach ($cats as $i => $cat) {
if ($cat->parent == $parentId) {
$into[$cat->term_id] = $cat;
unset($cats[$i]);
}
}
foreach ($into as $topCat) {
$topCat->children = array();
sortHierarchicalTaxonomy($cats, $topCat->children, $topCat->term_id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment