3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = array( [ "name" => "cat1", "id" => "1", "parent" => "", ], [ "name" => "cat2", "id" => "2", "parent" => "", ], [ "name" => "subcat1", "id" => "6", "parent" => "1", ], [ "name" => "subsubcat1", "id" => "7", "parent" => "6", ], [ "name" => "subcat2", "id" => "5", "parent" => "2", ], ); function list_item($arr, $item) { echo "<li>{$item['name']}</li>\n"; // find any children $children = array_filter($arr, function ($i) use ($item) { return $i['parent'] == $item['id']; }); if (!empty($children)) { echo "<ul>\n"; foreach ($children as $child) { list_item($arr, $child); } echo "</ul>\n"; } } $parents = array_filter($arr, function ($item) { return !$item['parent'];}); echo "<ul>\n"; foreach ($parents as $parent) { list_item($arr, $parent); } echo "</ul>\n";
Output for 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.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.14
<ul> <li>cat1</li> <ul> <li>subcat1</li> <ul> <li>subsubcat1</li> </ul> </ul> <li>cat2</li> <ul> <li>subcat2</li> </ul> </ul>

preferences:
80.74 ms | 407 KiB | 5 Q