I have a bunch of name-parentname pairs, that I\'d like to turn into as few heirarchical tree structures as possible. So for example, these could be the pairings:
Here's what I came up with:
$arr = array(
'H' => 'G',
'F' => 'G',
'G' => 'D',
'E' => 'D',
'A' => 'E',
'B' => 'C',
'C' => 'E',
'D' => null );
$nested = parentChild($arr);
print_r($nested);
function parentChild(&$arr, $parent = false) {
if( !$parent) { //initial call
$rootKey = array_search( null, $arr);
return array($rootKey => parentChild($arr, $rootKey));
}else { // recursing through
$keys = array_keys($arr, $parent);
$piece = array();
if($keys) { // found children, so handle them
if( !is_array($keys) ) { // only one child
$piece = parentChild($arr, $keys);
}else{ // multiple children
foreach( $keys as $key ){
$piece[$key] = parentChild($arr, $key);
}
}
}else {
return $parent; //return the main tag (no kids)
}
return $piece; // return the array built via recursion
}
}
outputs:
Array
(
[D] => Array
(
[G] => Array
(
[H] => H
[F] => F
)
[E] => Array
(
[A] => A
[C] => Array
(
[B] => B
)
)
)
)