2010-11-17 86 views
0

我有一個文檔數組,其中每個文檔都有另一個簡單的一維數組facet(簡單的文本標籤附加到文檔),它們具有結構性值順序(0從最接近的根到邊緣)。我正在遍歷這個數組,並且想創建一個多維數組,就像樹結構一樣。所以,像這些文件中的一個這樣的片段,使用更簡單的PHP數組創建多維數組

Array ('document-001' => Array (
    Array ('facets' => array (
     'Public - Policy and Procedures', 
     'Employment Services Manual', 
     'Section 02 - Recruitment & Selection', 
    ) 
    ... many more here ... 
) ; 

我想要這個;

Array 
(
    [Public - Policy and Procedures] => Array (
      [Administration Manual] => Array () 
      [Corporate Governance Manual] => Array () 
      [Food Services Manual] => Array () 
      [Charter Manual] => Array () 
      [Infection Control Manual] => Array () 
      [Leisure and Lifestyle Manual] => Array () 
      [Employment Services Manual] => Array (
        [Section 09 - Termination & Resignation] => Array () 
        [Section 02 - Recruitment & Selection] => Array () 
        [Section 10 - Security] => Array () 
      ) 
      [Environmental Sustainability Manual] => Array (
        [Property - New Development & Refurbishment Policy 5.5] => Array () 
      ) 
    ) 

我目前的解決方案非常不雅,其中$ index是我的新多維數組;

// Pick out the facets array from my larger $docs array 
$t = $docs['facets'] ; 
$c = count ($t) ; 

if  ($c == 2) $index[$t[0]] = array() ; 
else if ($c == 3) $index[$t[0]][$t[1]] = array() ; 
else if ($c == 4) $index[$t[0]][$t[1]][$t[2]] = array() ; 
else if ($c == 5) $index[$t[0]][$t[1]][$t[2]][$t[3]] = array() ; 
else if ($c == 6) $index[$t[0]][$t[1]][$t[2]][$t[3]][$t[4]] = array() ; 
else if ($c == 7) $index[$t[0]][$t[1]][$t[2]][$t[3]][$t[4]][$t[5]] = array() ; 

當然有更好的方法。我已經蹣跚學步了各種陣列功能,但沒有什麼突出的解決方案。這裏的問題是動態主義與PHP本身的語法作戰。我當然可以創建一個面向對象的解決方案,但這是一個簡單的小遍歷,我不想去那裏(即使我可能應該)。

想法?

回答

2

只需使用一些遞歸:

function bar($source, $dest){ 
    if(count($source) == 0){ 
     return array(); 
    } 
    $dest[$source[0]] = bar(array_slice($source, 1), $dest[$source[0]]); 
    return $dest; 
} 

$t = $docsA['facets']; 
$s = $docsB['facets']; 

$index = array(); 
$index = bar($t, $index); 
$index = bar($s, $index); 
+0

這是卓有成效的,儘管它不是最終的解決方案(性能是非常大的集合有點慢,和我的一些數以千計ducuments的):)但是,它完成了這項工作,我將嘗試調整它的性能(整理數組,預先標記標籤等)。謝謝! – AlexanderJohannesen 2010-11-17 23:11:48

+0

@Alexander它可能會更快,如果它在原地修改數組而不是返回它,但我會把它作爲一個練習。它涉及聲明'$ dest'爲'&$ dest',我相信,但我對PHP中的by-reference語法很朦朧。 – 2010-11-18 01:25:48