2016-09-19 37 views
1

我想從PHP決策樹得到所有的可能性都不同路徑的可能性,我的輸入是這樣的:查找PHP數組

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 
    ), 
... 

如果空值被擊中,路徑是否完整。

第一級關鍵是現場ID,第二個層次是選擇id作爲鍵和下一個場景的id值。

我無法弄清楚如何處理這個問題,我想這樣的遞歸函數:

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]); 

但它僅適用於第一種可能性,我認爲我接近的解決方案? 問題是結束條件,以及如何避免重複。

非常感謝您的幫助。

編輯:預期結果數組應該是這樣的:

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

你希望從** myRecursive($ scenesArray [62])得到什麼樣的輸出; ** – developer

+0

沒有具體的輸出,我只是想將scene_id放在$ result數組中,爲我當前的可能性 – Ben

+0

,所以你插入62 ,那是什麼?用戶所做的選擇?那麼你是否爲用戶定義了所有節點的所有可能路徑?或者您是否需要每個可以到達的指向null的id? –

回答

0
<?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); 

?> 

如果拼合$finalArray,那麼,你得到的數組鍵的獨特的可能性。

+0

由於樣本Verhaeghe先生,這很有用! – Ben