一尘不染

嵌套数组。第三层正在消失

php

我有那个数组:

$a = array(
    "7" => array(
        "id" => 7,
        "parent" => 6
    ),
    "6" => array(
        "id" => 6,
        "parent" => 5
    ),
    "5" => array(
        "id" => 5,
        "parent" => 4
    ),
    "4" => array(
        "id" => 4,
        "parent" => 0
    ),
    "3" => array(
        "id" => 7,
        "parent" => 2
    ),
    "2" => array(
        "id" => 7,
        "parent" => 1
    ),
    "1" => array(
        "id" => 7,
        "parent" => 0
    )
);

我想要的结果是:

$a = array(
    "4" => array(
        "id" => 4,
        "parent" => 0,
        array(
            "5" => array(
                "id" => 5,
                "parent" => 4,
                array(
                    "6" => array(
                        "id" => 6,
                        "parent" => 5,
                        array(
                            "7" => array(
                                "id" => 7,
                                "parent" => 6
                            )
                        )
                    )
                )
            )
        )
    ),
    "2" => array(
        "id" => 7,
        "parent" => 1,
        array(
            "3" => array(
                "id" => 7,
                "parent" => 2
            )
        )
    ),
    "1" => array(
        "id" => 7,
        "parent" => 0
    )
);

我使用的代码是这样的:

foreach($a as $v)
{
    if(isset($a[$v['PARENT']]))
    {
        $a[$v['PARENT']][$v['ID']] = $v;
        unset($a[$v['ID']]);
    }
}

我的问题是我得到了那个结果:

$a = array(
    "4" => array(
        "id" => 4,
        "parent" => 0,
        array(
            "5" => array(
                "id" => 5,
                "parent" => 4
            )
        )
    ),
    "2" => array(
        "id" => 7,
        "parent" => 1,
        array(
            "3" => array(
                "id" => 7,
                "parent" => 2
            )
        )
    ),
    "1" => array(
        "id" => 7,
        "parent" => 0
    )
);

而不是需要它的结果。


阅读 308

收藏
2020-05-29

共1个答案

一尘不染

要解决您的问题,您需要正确地理解PHP中变量引用/别名的工作方式。

看下面的示例代码,它看起来与您的代码没有太大不同,但是利用引用来访问任何父对象,即使它已经“移动”了:

# 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现在包含$flat- 中的所有值,但已重新排序。

2020-05-29