Last active
August 29, 2015 14:01
-
-
Save pfote/699aba15a7e665de1331 to your computer and use it in GitHub Desktop.
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 | |
$list = array( | |
array('page_id' => '3', | |
'url' => '/johtamisjarjestelma/yritys', | |
'title' => 'Yritys'), | |
array( | |
'page_id' => '4', | |
'url' => '/johtamisjarjestelma/yritys/historia', | |
'title' => 'Historia'), | |
array( | |
'page_id' => '5', | |
'url' => '/johtamisjarjestelma/testing', | |
'title' => 'Testing'), | |
array( | |
'page_id' => '6', | |
'url' => '/johtamisjarjestelma/testing/moartesting', | |
'title' => 'More testing') | |
); | |
function build_tree(&$tree, &$path, $attribs) { | |
/* get (and remove) first child from path */ | |
$elem = array_shift($path); | |
if ($elem) { | |
if (! array_key_exists($elem, $tree)){ | |
/* create a new child if not exist */ | |
$tree[$elem] = array(); | |
} | |
build_tree($tree[$elem], $path, $attribs); | |
} else { | |
/* if its a end node, add title and id */ | |
if ($tree == array()) { | |
$tree = $attribs; | |
} else { | |
$tree = array_merge($tree, $attribs); | |
} | |
} | |
} | |
function render_tree($tree, &$output) { | |
if (count($tree)) { /* more than zero elements */ | |
$output .= "<ul>"; | |
foreach($tree as $key => $val) { | |
if (substr($key, 0, 2) != '__') { | |
$output .= "<li>" . $key . "</li>"; | |
if (is_array($val)) { /* check for childs */ | |
render_tree($tree[$key], $output); | |
} | |
} | |
} | |
$output .= "</ul>"; | |
} | |
} | |
$tree = array(); | |
foreach($list as $elem) { | |
$path = explode('/', $elem['url']); | |
array_shift($path); /* first element is empty */ | |
/* recursively build a tree */ | |
build_tree($tree, $path, array('__page' => $elem['page_id'], | |
'__title' => $elem['title'], | |
'__url' =>$elem['url'])); | |
} | |
$output = ''; | |
render_tree($tree, $output); | |
echo $output; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment