Skip to content

Instantly share code, notes, and snippets.

@Maxwell2022
Last active December 27, 2015 13:19
Show Gist options
  • Save Maxwell2022/7331963 to your computer and use it in GitHub Desktop.
Save Maxwell2022/7331963 to your computer and use it in GitHub Desktop.
Create a tree structure from a flat structure efficiently using variable addresses
protected function getCategoryTree()
{
// IMPORTANT: Return categories sorted by parent_id ASC
$categories = $this->em->getRepository('ZumnyCoreBundle:Category')->findAll();
$flat = array();
$tree = array();
/** @var EntityCategory $category */
foreach ($categories as $category) {
$category = $category->toArray();
$category['children'] = array();
if (!isset($flat[$category['id']])) {
$flat[$category['id']] = $category;
}
if (null == $category['parent']) {
$tree[] = &$flat[$category['id']];
} else {
$flat[$category['parent']]['children'][$category['id']] = &$flat[$category['id']];
}
}
return $tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment