2013-03-04 64 views
0

我有這個任務的麻煩。即時通訊新的PHP。 我想我一定用戶遞歸funcruion,但我不明白它是如何使用從PHP中的direcory數組樹中獲取目錄路徑

我有一個這樣的數組:

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [parent_id] => 0 
      [name] => New Folder 
     ) 
    [1] => Array (
      [id] => 2 
      [parent_id] => 1 
      [name] => New Folder2 
     ) 
    [2] => Array 
     (
      [id] => 3 
      [parent_id] => 2 
      [name] => New Folder3 
     ) 
    ...... 
    [5] => Array 
     (
      [id] => 6 
      [parent_id] => 0 
      [name] => New Folder6 
     ) 
    [6] => Array (
      [id] => 7 
      [parent_id] => 6 
      [name] => New Folder7 
     ) 
    [7] => Array 
     (
      [id] => 8 
      [parent_id] => 6 
      [name] => New Folder8 
     ) 
) 

我需要建立這樣的豬病的路徑:

/New Folder 
/New Folder/New Folder2 
/New Folder/New Folder2/New Folder3 
... 
/New Folder6 
/New Folder6/New Folder7 
/New Folder6/New Folder8 

你能幫我完成這個任務嗎? Thx。

+0

開始與一些[通用樹構建](http://stackoverflow.com/questions/8587341/recursive-function-to-generate-multidimensional-array-from-database-result)構建一個多維數組代表樹。利用遞歸函數中新獲得的技能,遍歷該樹並構建路徑。 – deceze 2013-03-04 11:10:21

回答

0
$txtTree[0]="/"; 

foreach($treeArray as $branch){ 

    if(isset($txtTree[$branch['parent_id']])) { 
     $txtTree[$branch['id']] = $txtTree[$branch['parent_id']] . $branch['name']. "/"; 
    } 
} 

print_r($txtTree); 


Array 
(
    [0] =>/
    [1] => /New Folder/ 
    [2] => /New Folder/New Folder2/ 
    [3] => /New Folder/New Folder2/New Folder3/ 
    [6] => /New Folder6/ 
    [7] => /New Folder6/New Folder7/ 
    [8] => /New Folder6/New Folder8/ 
) 
+0

這太棒了!謝謝! – kuai6 2013-03-04 12:49:25