I have a multidimensional array that looks like this:
$trees = array(
array(
\'name\' => \'Parent\',
\'__children\' => array(
Ok I have given this a shot and although it might not be the cleanest solution I think it should get the job done:
function flattenRecursive(array &$flat, $parentkey, array $nested){
$flag = true;
$prepend = '';
foreach( $nested as $k => $val ){
if( is_array($val) ){
if ( $k == '__children' && $flag) {
$prepend = end($flat);
$flag = true;
} else {
$flag = false;
}
flattenRecursive($flat, $prepend , $val);
} else {
$flat[] = $parentkey . ' ' . $val;
}
}
}
function flatten(array $nested){
$flat = array();
flattenRecursive($flat, '', $nested);
return $flat;
}
On a test array (with extra nesting for extra testing) as follows
$trees = array(
array(
'name' => 'Parent',
'__children' => array(
array(
'name' => 'Child',
'__children' => array(
array(
'name' => 'Nest One'
),
array(
'name' => 'Nest Two'
)
)
),
array(
'name' => 'Second Child'
)
)
)
);
$result = flatten($trees);
the var_dump
of $result
looks like the following
array(5) {
[0]=>
string(7) " Parent"
[1]=>
string(13) " Parent Child"
[2]=>
string(22) " Parent Child Nest One"
[3]=>
string(22) " Parent Child Nest Two"
[4]=>
string(20) " Parent Second Child"
}
Hopefully this was what you were looking for