Skip to content

Instantly share code, notes, and snippets.

Last active Nov 15, 2021
What would you like to do?
Quick and easy way to translate flat arrays into nested arrays in PHP.
* Wrapper to get terms in a nested fashion.
* This gets a little complicated. Basically, we're creating a placeholder in
* $children to hold the child terms of each parent term. Then we create a
* reference to that element in the parent term. So nesting happens via magic.
public function get_terms_nested($args)
$temp_terms = $this->get_terms($args);
$terms = array();
$children = array();
foreach($temp_terms as $term)
// Create a placeholder for the object's children.
$children[$term['id']] = array();
// Create a link to those children.
$term['children'] = &$children[$term['id']];
if (!strlen($term['parent_id']))
$terms[] = $term;
// Create a placeholder for the parent.
$children[$term['parent_id']] = array();
// Add this object to the parent, even if it doesn't exist yet.
$children[$term['parent_id']][] = $term;
return $terms;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment