2010-11-17 89 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