Ben Ben - 2 months ago 5
PHP Question

Find all distinct path possibilities from php array

I'm trying to get all possibilities from a decision tree in PHP, my input looks like this :

array(
(int) 61 => array(
(int) 257 => '62'
),
(int) 62 => array(
(int) 258 => '63',
(int) 259 => '63',
(int) 260 => '64',
(int) 261 => null
),
(int) 63 => array(
(int) 262 => '65',
(int) 263 => '65',
(int) 264 => '66',
(int) 265 => '69'
),
(int) 64 => array(
(int) 266 => '65',
(int) 267 => '66',
(int) 268 => '66',
(int) 269 => null
),
...


If null value is hit, path is complete.

First level key is the scene id, second level are the choices id as key and the next scene id as value.

I can't figure out how to handle this problem, I tried a recursive function like this :

function myRecursive($dialogs) {

foreach($dialogs as $i => $scene_to_go) {
if(empty($scene_to_go)) {
$index++;
} else {
$result[$index][] = $scene_to_go;
myRecursive($scenesArray[$scene_to_go]);
}

}

}

myRecursive($scenesArray[61]);


But it only works for the first possibility, I think I'm close to the solution ?
Problem is the ending condition, and how to avoid duplicates.

Thank you very much for your help.

EDIT : Expected result array should look like :

[
[61, 62, 63, 65],
[61, 62, 64, 65],
...
]

Answer
<?php
   public function getNextScenes($sceneId, &$nextDialogsArray) {
        global $array;
        foreach($array[$sceneId] as $dialogId => $nextSceneId) {
            $nextDialogsArray[$dialogId] = [];

            if (!empty($nextSceneId)) {
                $this->getNextScenes($nextSceneId, $nextDialogsArray[$dialogId]);
            }
        }
    }

    global $array;

    $array = [/**/]; // The input array you mentionned up there

    $finalArray = [];

    $this->getNextScenes(61, $finalArray);

?>

If you flatten the $finalArray, then, you got the unique possibilities in the array keys.