Converting a flat array to a nested array
- by matte
Hi,
I am trying to convert a flat array to a nested array depending on the 'level' data of each array item. 'level' data shows us if current array item is a child, a parent or a sibling.
Here is the flat array:
$sequentialArray = array(
array('title'=>'Page 1', 'level'=>0),
array('title'=>'Page 2', 'level'=>0),
array('title'=>'Page 3', 'level'=>1),
array('title'=>'Page 4', 'level'=>1),
array('title'=>'Page 5', 'level'=>2),
array('title'=>'Page 6', 'level'=>0),
array('title'=>'Page 7', 'level'=>1),
array('title'=>'Page 8', 'level'=>0)
);
And here is the expected result:
$nestedArray = array(
array('title'=>'Page 1', 'children'=>array()),
array('title'=>'Page 2', 'children'=>array(
array('title'=>'Page 3', 'children'=>array()),
array('title'=>'Page 4', 'children'=>array(
array('title'=>'Page 5', 'children'=>array())
)),
)),
array('title'=>'Page 6', 'children'=>array(
array('title'=>'Page 7', 'children'=>array())
)),
array('title'=>'Page 8', 'children'=>array()),
);
I tried using references with array indexes but that didn't work. Any ideas?