Skip to content

Instantly share code, notes, and snippets.

@krusynth
Last active Nov 15, 2021
Embed
What would you like to do?
Quick and easy way to translate flat arrays into nested arrays in PHP.
<?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.
if(!isset($children[$term['id']]))
{
$children[$term['id']] = array();
}
// Create a link to those children.
$term['children'] = &$children[$term['id']];
if (!strlen($term['parent_id']))
{
$terms[] = $term;
}
else
{
// Create a placeholder for the parent.
if(!isset($children[$term['parent_id']]))
{
$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