2

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:

$flatArray = 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.

1 Answer 1

3

Does this help? I think it does the right thing...maybe :D Sorry if it doesn't.

$nestedArray = array();

foreach ($flatArray as $key => $value) {
  $current = &$nestedArray;
  $level = $value['level'];
  while ($level > 0) {
    $last = &$current[count($current) - 1];
    $current = &$last['children'];
    --$level;
  }
  $current[] = array('title' => $value['title'], 'children' => array());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.