Reputation: 2028
I have an array of documents, where each document have another simple one-dimensional array of facets (simple textual labels attached to the document) that have structural value in their order (0 from nearest the root to the edges). I'm traversing this array, and would like to create a multi-dimensional array, like a tree-structure. So, having something like this fragment of just one of those documents ;
Array ( 'document-001' => Array (
Array ( 'facets' => array (
'Public - Policy and Procedures',
'Employment Services Manual',
'Section 02 - Recruitment & Selection',
)
... many more here ...
) ;
I want this ;
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 ( )
)
)
My current solution is highly inelegant, where $index is my new multi-dimensional array ;
// 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() ;
Surely there's a better way. I've troddled through the various array functions, but nothing stands out as an obvious solution. The problem here is that the dynamicism battles against the syntax of PHP itself. I could of course create an OO solution, but this is such a simple little traverse I don't really want to go there (even though I probably should).
Thoughts?
Upvotes: 0
Views: 1218
Reputation: 77034
Just use some recursion:
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);
Upvotes: 2