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; }

preferences:
25.16 ms | 405 KiB | 5 Q