Nested array. Third level is disappearing

后端 未结 2 927
迷失自我
迷失自我 2020-11-27 08:23

I have that array :

$a = array(
    \"7\" => array(
        \"id\" => 7,
        \"parent\" => 6
    ),
    \"6\" => array(
        \"id\" =>         


        
2条回答
  •  温柔的废话
    2020-11-27 08:41

    To solve your problem you need to properly understand how variable referencing/aliasing in PHP works.

    Look at the following example code, which does not look much different to yours but makes use of references in order to access any parent even it has already "moved":

    # transform $flat into a tree:
    foreach($flat as $id => &$value)
    {
        # check if there is a parent
        if ($parentId = $value['parent'])
        {
            $flat[$parentId][0][$id] =& $value; # add child to parent
            unset($flat[$id]); # remove reference from topmost level
        }
    }
    unset($value); # remove iterator reference
    print_r($flat); # your tree
    

    $flat now contains all values from $flat - but reordered. Demo.

提交回复
热议问题