Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function add_branch($tree, $branch){
- /*
- $tree is the pre-existing tree, and $branch is the branch that is to be added to the tree.
- */
- $temp = &$tree;
- foreach($branch as $node){
- if(array_key_exists($node, $temp)){
- $temp = &$temp[$node];
- }else{
- $temp[$node] = array();
- $temp = &$temp[$node];
- }
- }
- return $tree;
- }
- $tree = array();
- $branch = array("1", "2", "3", "4", "5");
- $tree = add_branch($tree, $branch);
- $branch = array("1", "2", "5");
- $tree = add_branch($tree, $branch);
- print_r($tree);
- /*this produces:
- Array
- (
- [1] => Array
- (
- [2] => Array
- (
- [3] => Array
- (
- [4] => Array
- (
- [5] => Array
- (
- )
- )
- )
- [5] => Array
- (
- )
- )
- )
- )
- */
Advertisement
Add Comment
Please, Sign In to add comment