开发者

Converting a flat array to a nested array

开发者 https://www.devze.com 2022-12-28 06:09 出处:网络
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.

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'=>'Pag开发者_JAVA百科e 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.


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());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号