Skip to content

Instantly share code, notes, and snippets.

@uxjw
Last active August 29, 2015 14:20
Show Gist options
  • Save uxjw/05f723be261741492bc3 to your computer and use it in GitHub Desktop.
Save uxjw/05f723be261741492bc3 to your computer and use it in GitHub Desktop.
PHP Associative array to tree
<?php
// Converts an array of single rows with a parent id column into a tree
function tree($rows){
// supplied array must be indexed by row id
$tree = array(); //stores the tree
$tree_index = array(); //an array used to quickly find nodes in the tree
$id_column = "id"; //The column that contains the id of each node
$parent_column = "parent"; //The column that contains the id of each node's parent
//build the tree - this will complete in a single pass if no parents are defined after children
while(count($rows) > 0){
foreach($rows as $row_id => $row){
if($row[$parent_column]){
if((!array_key_exists($row[$parent_column], $rows)) and (!array_key_exists($row[$parent_column], $tree_index))){
unset($rows[$row_id]);
}
else{
if(array_key_exists($row[$parent_column], $tree_index)){
$parent = & $tree_index[$row[$parent_column]];
$parent['children'][$row_id] = array("node" => $row, "children" => array());
$tree_index[$row_id] = & $parent['children'][$row_id];
unset($rows[$row_id]);
}
}
}
else{
$tree[$row_id] = array("node" => $row, "children" => array());
$tree_index[$row_id] = & $tree[$row_id];
unset($rows[$row_id]);
}
}
}
//we are done with index now so free it
unset($tree_index);
return($tree);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment