Created
August 19, 2012 13:28
-
-
Save jmc734/3394779 to your computer and use it in GitHub Desktop.
Build a tree structure from an array of nodes with IDs and parent IDs
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
<?php | |
class Structure { | |
private static $structure; | |
private static $lookup; | |
// Nodes can be any objects that have IDs (id) and a parent IDs (parent) | |
public static function buildTree($nodes){ | |
// Initialize structure and lookup arrays | |
self::$structure = array(); | |
self::$lookup = array(); | |
// Walk through nodes | |
array_walk($nodes, 'Structure::addNode'); | |
// Return the hierarchical (tree) structure | |
return self::$structure; | |
} | |
private static function addNode($obj) { | |
// Convert string ids returned by PDO to integers | |
$nid = (int)$obj->id; | |
$pid = (int)$obj->parent; | |
// Initialize child array | |
$obj->children = array(); | |
// If top level node, set parent child array to a reference to whole structure | |
if($pid === 0){ | |
// If top level node, set parent child array to whole structure | |
$parent = &self::$structure; | |
} else { | |
// Else, set it to reference to the parent child array | |
$parent = &self::$lookup[$pid]->children; | |
} | |
// Get ID of new node it child array | |
$id = count($parent); | |
// Add node to child array | |
$parent[] = $obj; | |
// Add reference to node in parent child array to the lookup table | |
self::$lookup[$nid] = &$parent[$id]; | |
} | |
/* ... */ | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage?