3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<style> ul{ list-style: none; } li { position: relative; margin-left: -15px; list-style: none; } </style><?php $arr = array ( '192.168.10.216' => '192.168.40.103', '192.168.10.217' => '192.168.10.216', '192.168.10.88' => '192.168.10.216', '192.168.40.102' => NULL, '192.168.40.103' => '192.168.40.102', '192.168.40.104' => '192.168.40.102' ); function parseTree($tree, $root = null) { $return = array(); # Traverse the tree and search for direct children of the root foreach($tree as $child => $parent) { # A direct child is found if($parent == $root) { # Remove item from tree (we don't need to traverse this again) unset($tree[$child]); # Append the child into result array and parse its children $return[] = array( 'name' => $child, 'children' => parseTree($tree, $child) ); } } return empty($return) ? null : $return; } function printtree($tree) { if(!is_null($tree) && count($tree) > 0) { echo '<ul>'; foreach($tree as $b) { echo '<li>'.$b['name']; printtree($b['children']); echo '</li>'; } echo '</ul>'; } } printtree(parseTree($arr));
Output for 4.3.0 - 7.1.0
<style> ul{ list-style: none; } li { position: relative; margin-left: -15px; list-style: none; } </style><ul><li>192.168.40.102<ul><li>192.168.40.103<ul><li>192.168.10.216<ul><li>192.168.10.217</li><li>192.168.10.88</li></ul></li></ul></li><li>192.168.40.104</li></ul></li></ul>