Pass the array recursively, preserving a complete journey from beginning to end?

There is an array:
$arr = [
 2 => [
 3 => [
 5 => [],
 7 => [
 12 => [],
 15 => []
]
],
 4 => [],
 7 => [
 12 => [],
 15 => []
]
],
 9 => [
 11 => [
 7 => [
 12 => [],
 15 => [] 
],
 4 => [],
 5 => []
]
]
];


How to get it to the way looked like:
2->3->5
2->3->7->12
2->3->7->15
2->4
2->7->12
2->7->15, etc.

Wrote such code:
$path = [];

function rec($arr, &$path) {
 foreach ($arr as $id => $branch) {
 $path[] = $id;

 if ($branch) {
 rec($branch, $path);
 } else {
var_dump($path);
 $path = [];
}
}
}

rec($arr, $path);


But he obviously starts every time from the very beginning.
April 4th 20 at 00:43
1 answer
April 4th 20 at 00:45
Solution
function getPaths($arr, $currPath = []) {
 $paths = [];

 foreach ($arr as $key => $val) {
 $currPath[] = $key;

 array_push($paths, ...(is_array($val) && !empty($val)
 ? getPaths($val, $currPath)
 : [ $currPath ]
));

array_pop($currPath);
}

 return $paths;
}


$paths = getPaths($arr);
The essence of how I (after revision of my code, I also entered the $currentPath, but haven't updated the post), you only remove the last element of the current path, and instead, there is another, "imitating" a new passage from the beginning. Interesting was the real passage, but, really, the problem is solved, good. In any case, thank you very much. - Madisen_Pacocha commented on April 4th 20 at 00:48

Find more questions by tags PHPRecursion