I have a multidimensional array that looks like this:
$trees = array(
array(
'name' => 'Parent',
'__children' => array(
array(
'name' => 'Child'
),
array(
'name' => 'Second Child'
)
)
)
);
The depth of the array is unknown and I need to recursively flatten it. So it looks more like this:
array(
array(
'name' => 'Parent'
),
array(
'name' => 'Child'
),
array(
'name' => 'Second Child'
)
)
I thought something like this might work:
public function flattenTree($trees, $tree = array())
{
foreach($trees as $item){
//$i = 1, 2, then 3
$i = count($tree);
$tree[$i] = array('name' => $item['name']);
if(isset($item['__children']))
$this->flattenTree($item['__children'], $tree);
}
return $tree;
}
But this is only gives me :(
Array
(
[0] => Array
(
[name] => Parent
)
)
I am unsure how to do this. Is it possible?
As a bonus I really need the output array to look like this(notice the name value changed) :)
array(
array(
'name' => 'Parent'
),
array(
'name' => 'Parent Child'
),
array(
'name' => 'Parent Second Child'
)
)
Thanks a ton for the help on this one. Looking forward to the solutions. I am stumped!