Last active
December 27, 2015 13:19
-
-
Save Maxwell2022/7331963 to your computer and use it in GitHub Desktop.
Create a tree structure from a flat structure efficiently using variable addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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