Last active
August 29, 2015 14:20
-
-
Save uxjw/05f723be261741492bc3 to your computer and use it in GitHub Desktop.
PHP Associative array to tree
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 | |
// 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