3v4l.org

run code in 300+ PHP versions simultaneously
<?php $locations = array( 3 => array("Building", 2), 2 => array("Area", 1), 0 => array("Floor", 3), 1 => array("City"), 4 => array("Room", 0), 13 => array("Building1", 12), 12 => array("Area1", 11), 14 => array("Room1", 10), 10 => array("Floor1", 13), 11 => array("City1") ); $dic = []; $roots = []; foreach($locations as $k => $e) { if (count($e) == 2) $dic[$e[1]] = $k; else $roots[] = $k; } foreach($roots as $root) { $path = []; $node = $root; while (isset($dic[$node])) { $path[] = $locations[$node][0]; $node = $dic[$node]; } $path[] = $locations[$node][0]; echo implode(",", array_reverse($path)) . PHP_EOL; }
Output for 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.30, 8.2.0 - 8.2.24, 8.3.0 - 8.3.12
Room,Floor,Building,Area,City Room1,Floor1,Building1,Area1,City1

preferences:
77.81 ms | 407 KiB | 5 Q