0

我有一个看起来像这样的数组:

$someArray = array(
array(
    "id"=> 1,
    "name"=> "somename1",
    "parent"=> 0
),
array(
    "id"=> 53,
    "name"=> "somename2",
    "parent"=> 1
),
array(
    "id"=> 921,
    "name"=> "somename3",
    "parent"=> 53,
)
.
.
.
.
.
.
);

Ofcs 数组中有更多单元格,这只是一小部分

我正在尝试将此数组转换为:

$someArray = array(
array(
    "id"=> 1,
    "name"=> "somename1",
    "parent"=> 0,
    "children" => array(
        array(
            "id"=> 53,
            "name"=> "somename2",
            "parent"=> 1,
            "children" => array(
                array(
                    "id"=> 921,
                    "name"=> "somename3",
                    "parent"=> 53,
                    "children" => array(

                    )
                )
            )
        )
    )
)

.
.
.
.
.
.
);

我试了一天半,似乎无法完成。

先谢谢了。

4

1 回答 1

0
/*
    Gets reversed array,
    Returns multidimensional tree array.
*/
function buildTree($parts) {
    if (count($parts) == 1) {
        return $parts[0];
    }
    $last_item = array_pop($parts);
    $last_item[] = buildTree($parts);
    return $last_item;
}

测试:

$parts = array(
            array('1','2','3',5),
            array('3','8','3',1),
            array('1', 5,'2','3'),
            array('D','2','3',5),
            array('A','2','3',5)
        );

var_dump(buildTree(array_reverse($parts)));

输出:

array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(5) {
    [0]=> string(1) "3" [1]=> string(1) "8" [2]=> string(1) "3" [3]=> int(1) [4]=> array(5) {
        [0]=> string(1) "1" [1]=> int(5) [2]=> string(1) "2" [3]=> string(1) "3" [4]=> array(5) {
            [0]=> string(1) "D" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) [4]=> array(4) {
                [0]=> string(1) "A" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> int(5) 
} } } } }
于 2013-06-02T23:05:11.657 回答