3v4l.org

run code in 300+ PHP versions simultaneously
<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 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
<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>

preferences:
335.75 ms | 406 KiB | 459 Q