从多维PHP数组创建数组树

时间:2018-01-28 21:56:49

标签: php arrays multidimensional-array

我正在尝试构建一个注释层次结构,因此有些必须嵌套在一起。

初始数组是这样的:

$comments = [
    [   
        'id'=> 1, 
        'parent_id'=> null,
        'children'=> [],
    ],
    [   
        'id'=> 2, 
        'parent_id'=> null,
        'children'=> [],
    ],
    [   
        'id'=> 3, 
        'parent_id'=> null,
        'children'=> [],
    ],
    [   
        'id'=> 4, 
        'parent_id'=> 2,
        'children'=> [],
    ],
    [   
        'id'=> 5, 
        'parent_id'=> 3,
        'children'=> [],
    ],
    [   
        'id'=> 6, 
        'parent_id'=> 4,
        'children'=> [],
    ],
    [   
        'id'=> 7, 
        'parent_id'=> 4,
        'children'=> [],
    ],
];

上述数组的输出应该是这样的:

$comments = [
    [   
        'id'=> 1, 
        'parent_id'=> null,
        'children'=> [],
    ],
    [   
        'id'=> 2, 
        'parent_id'=> null,
        'children'=> [
            [   
                'id'=> 4, 
                'parent_id'=> 2,
                'children'=> [
                    [   
                        'id'=> 6, 
                        'parent_id'=> 4,
                        'children'=> [],
                    ],
                    [   
                        'id'=> 7, 
                        'parent_id'=> 4,
                        'children'=> [],
                    ],
                ],
            ],
        ],
    ],
    [   
        'id'=> 3, 
        'parent_id'=> null,
        'children'=> [
            [   
                'id'=> 5, 
                'parent_id'=> 3,
                'children'=> [],
            ],
        ],
    ],
];

我的下面的代码得到了正确的顶部但是错过了二级孩子:

// organize comments into a hierarchy
$tree = array_map(function($comment) use ($comments) {
    $children = [];
    $comments = array_map(function($child) use ($comment, &$children) {
        // return [$child['parent_id'], $comment['id']];
        if($child['parent_id'] == $comment['id']){
            $children[] = $child;
        }
        return $child;
    }, $comments);
    $comment['children'] = $children;
    return $comment;
}, $comments);

// remove children from the top
return $comments = array_filter($tree, function($child) {
    return !$child['parent_id'];
});

1 个答案:

答案 0 :(得分:1)

您可以使用this answer中发布的代码(所以这个问题确实是重复的),但显然您必须注意这些差异:

  • 您的输入变量名称不同
  • 父属性名称略有不同
  • 根节点的值为 Error_vs_Correct Trial_Type 0 1 1 89 5646 2 25 804 3 140 672 4 21 815 ,而引用的答案中为0

由于最后一点,您必须将null作为第二个参数传递给$new[null]

以下是适用于您的变量名称的代码以及上述注释:

createTree