3v4l.org

run code in 200+ PHP versions simultaneously
<?php $menu = array( array(1,3,'Wurm 1.1', 2, 10), array(2,6,'Vogel 2.1', 2, 30), array(3,0,'Tiger 1', 1, 10), array(4,6,'Hund 2.2', 2, 40), array(5,3,'Katze 1.2', 2, 11), array(6,0,'Pferd 2', 1, 20), array(7,1,'Baer 1.1.1', 3, 0), array(8,3,'Schwein 1.3', 2, 12), array(9,4,'Esel 2.2.1', 3, 0), ); // Algorithmus hier uasort($menu, function($a,$b) { return $a[1] == $b[1] ? ($a[4] < $b[4] ? -1 : 1) : ($a[1] < $b[1] ? -1 : 1); }); $cache = array(); foreach ($menu as $m) { if (!isset($cache[$m[1]])) { $cache[$m[1]] = array(); } $cache[$m[1]][] = $m; } function m($m, $l, $r) { foreach($m[$l] as $e) { $r[] = $e; if (isset($m[$e[0]])) { $r = m($m, $e[0], $r); } } return $r; } $result = m($cache, 0, array()); //$result = m($menu, 0, array()); print_r($result); print_r($cache); $target = array( array(3,0,'Tiger 1', 1, 10), array(1,3,'Wurm 1.1', 2, 10), array(7,1,'Baer 1.1.1', 3, 0), array(5,3,'Katze 1.2', 2, 11), array(8,3,'Schwein 1.3', 2, 12), array(6,0,'Pferd 2', 1, 20), array(2,6,'Vogel 2.1', 2, 30), array(4,6,'Hund 2.2', 2, 40), array(9,4,'Esel 2.2.1', 3, 0), ); var_dump($result == $target);
based on eWpZI
Output for 5.4.1 - 7.4.0
Array ( [0] => Array ( [0] => 3 [1] => 0 [2] => Tiger 1 [3] => 1 [4] => 10 ) [1] => Array ( [0] => 1 [1] => 3 [2] => Wurm 1.1 [3] => 2 [4] => 10 ) [2] => Array ( [0] => 7 [1] => 1 [2] => Baer 1.1.1 [3] => 3 [4] => 0 ) [3] => Array ( [0] => 5 [1] => 3 [2] => Katze 1.2 [3] => 2 [4] => 11 ) [4] => Array ( [0] => 8 [1] => 3 [2] => Schwein 1.3 [3] => 2 [4] => 12 ) [5] => Array ( [0] => 6 [1] => 0 [2] => Pferd 2 [3] => 1 [4] => 20 ) [6] => Array ( [0] => 2 [1] => 6 [2] => Vogel 2.1 [3] => 2 [4] => 30 ) [7] => Array ( [0] => 4 [1] => 6 [2] => Hund 2.2 [3] => 2 [4] => 40 ) [8] => Array ( [0] => 9 [1] => 4 [2] => Esel 2.2.1 [3] => 3 [4] => 0 ) ) Array ( [0] => Array ( [0] => Array ( [0] => 3 [1] => 0 [2] => Tiger 1 [3] => 1 [4] => 10 ) [1] => Array ( [0] => 6 [1] => 0 [2] => Pferd 2 [3] => 1 [4] => 20 ) ) [1] => Array ( [0] => Array ( [0] => 7 [1] => 1 [2] => Baer 1.1.1 [3] => 3 [4] => 0 ) ) [3] => Array ( [0] => Array ( [0] => 1 [1] => 3 [2] => Wurm 1.1 [3] => 2 [4] => 10 ) [1] => Array ( [0] => 5 [1] => 3 [2] => Katze 1.2 [3] => 2 [4] => 11 ) [2] => Array ( [0] => 8 [1] => 3 [2] => Schwein 1.3 [3] => 2 [4] => 12 ) ) [4] => Array ( [0] => Array ( [0] => 9 [1] => 4 [2] => Esel 2.2.1 [3] => 3 [4] => 0 ) ) [6] => Array ( [0] => Array ( [0] => 2 [1] => 6 [2] => Vogel 2.1 [3] => 2 [4] => 30 ) [1] => Array ( [0] => 4 [1] => 6 [2] => Hund 2.2 [3] => 2 [4] => 40 ) ) ) bool(true)