3v4l.org

run code in 300+ PHP versions simultaneously
<?php $lists = array(array( array( 'id' => 1, 'parent' => 0, 'name' => 'Menu 1', ), array( 'id' => 2, 'parent' => 1, 'name' => 'Menu 2', ), array( 'id' => 3, 'parent' => 2, 'name' => 'Menu 3', ), array( 'id' => 4, 'parent' => 1, 'name' => 'Menu 4', ), array( 'id' => 5, 'parent' => 0, 'name' => 'Menu 5', ) )); function make_list($lists, $parent = 0) { $children = array_filter($lists[0], function ($v) use($parent) { return $v['parent'] == $parent; }); if (!count($children)) return; echo "<ul>\n"; foreach ($children as $child) { echo "<li>{$child['name']}</li>\n"; make_list($lists, $child['id']); } echo "</ul>\n"; } make_list($lists);
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.26, 7.4.0 - 7.4.14, 8.0.0
<ul> <li>Menu 1</li> <ul> <li>Menu 2</li> <ul> <li>Menu 3</li> </ul> <li>Menu 4</li> </ul> <li>Menu 5</li> </ul>