Last active
December 20, 2015 03:18
-
-
Save lucacervasio/6062172 to your computer and use it in GitHub Desktop.
Building a tree from plain strings
This file contains hidden or 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 | |
error_reporting(E_ALL); | |
ini_set("display_errors", 1); | |
class tree_item { | |
public $title = ''; | |
public $children = array(); | |
public function &has_child($title) { | |
foreach ($this->children as $c) { | |
if ($c->title == $title) { | |
return $c; | |
} | |
} | |
return null; | |
} | |
} | |
$nodes = array(); | |
$in = array( | |
'uno.due.tre.quattro', | |
'uno.due.otto.nove' | |
//'uno.cinque.sei.sette', | |
); | |
$root = new tree_item(); | |
$root->title = 'uno'; | |
foreach ($in as $item) { | |
$data = explode(".", $item); | |
$cur = &$root; | |
foreach ($data as $idx => $d) { | |
if ($idx == 0 && $root->title != $d) | |
throw new Exception("root node must be unique"); | |
if ($idx > 0) { | |
$node = &$cur->has_child($d); | |
if ($node == null) { | |
$tmp = new tree_item(); | |
$tmp->title = $d; | |
$cur->children[] = $tmp; | |
$size = count($cur->children); | |
$cur =&$cur->children[$size-1]; | |
} else { | |
$cur = &$node; | |
} | |
} | |
} | |
} | |
print_r($root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment