Converting a flat array to a nested array

Posted by matte on Stack Overflow See other posts from Stack Overflow or by matte
Published on 2010-04-22T07:19:44Z Indexed on 2010/04/22 7:23 UTC
Read the original article Hit count: 387

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about php5

Related posts about arrays