Reputation: 4771
I have array of users and every user can have parents:
array(6) {
guest => NULL
moderator => NULL
member => array(1) [ //username
0 => "guest" (5) //parent
]
user => array(1) [
0 => "member" (6)
]
admin => array(1) [
0 => "moderator" (9)
]
}
And I want to make tree view from this data. The result should look like this: http://www.phorum.org/phorum5/file.php/62/3237/treeview_lightweight_admin_screenshot.jpg
The result will be:
- guest
- member
- user
- moderator
- admin
EDIT:
I tried to write tree generator, but i dont know how use recursion.
private function generateTree($node)
{
$return = array();
if(is_array($node))
{
foreach($node as $user => $parents)
{
if(is_null($parents))
{
$return[$user] = null;
}
if(is_array($parents))
{
foreach($parents as $parent)
{
if(array_key_exists($parent, $return))
{
$return[$parent] = $user;
}
else
{
dump($user, $parent);
}
}
}
}
}
return $return;
}
return:
array(2) {
guest => "member" (6)
moderator => "admin" (5)
}
left:
user => array(1) [
0 => "member" (6)
]
Upvotes: 0
Views: 2188
Reputation: 3092
You can active this by making the HTML builder method recursive. Essentially, the method invokes itself with an incrementing level variable (level 1, 2, 3, 4..) until the ultimate level has been reached. Every level contributes to the HTML code, depending on the level. A typical example would be:
function render($treeData, &$html, $level = 0) {
foreach ($treeData->branches as $branch) {
render($branch, $level + 1);
}
$html .= '<div class="section-level-'.$level.'">'.$treeData->currentLevelData.'</div>';
}
$html = '';
render($treeData, $html);
This is of course pseudo-code. :)
Upvotes: 1
Reputation: 5375
If you want to debug you have some automatic views with var_dump($array)
(for HTML render) or print_r($array)
(plain text render).
For a custom view you have to loop on your array and write your own HTML
Upvotes: 0