Created
January 4, 2011 14:31
-
-
Save shanestillwell/764821 to your computer and use it in GitHub Desktop.
Converts a NestedSet array into a mutli-dimensional array (Hydrates the flat array returned by Doctrine)
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
/** | |
* original http://groups.google.com/group/doctrine-user/browse_thread/thread/8674c5f27de54e0c | |
*/ | |
public function toHierarchy($collection) | |
{ | |
// Trees mapped | |
$trees = array(); | |
$l = 0; | |
if (count($collection) > 0) { | |
// Node Stack. Used to help building the hierarchy | |
$stack = array(); | |
foreach ($collection as $node) { | |
$item = ($node instanceof Doctrine_Record) ? $node->toArray() : $node; | |
$item['__children'] = array(); | |
// Number of stack items | |
$l = count($stack); | |
// Check if we're dealing with different levels | |
while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { | |
array_pop($stack); | |
$l--; | |
} | |
// Stack is empty (we are inspecting the root) | |
if ($l == 0) { | |
// Assigning the root node | |
$i = count($trees); | |
$trees[$i] = $item; | |
$stack[] = & $trees[$i]; | |
} else { | |
// Add node to parent | |
$i = count($stack[$l - 1]['__children']); | |
$stack[$l - 1]['__children'][$i] = $item; | |
$stack[] = & $stack[$l - 1]['__children'][$i]; | |
} | |
} | |
} | |
return $trees; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment