我有一个文档数组,其中每个文档都有另一个简单的一维facet数组(附加到文档的简单文本标签),这些facet按顺序具有结构值(从最接近根到边的0)。我正在遍历这个数组,并希望创建一个多维数组,类似于树结构。所以,只有一份文件的碎片;
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本身的语法格格不入。我当然可以创建一个面向对象的解决方案,但这是一个非常简单的小遍历,我不想去那里(尽管我可能应该去)。
思想?