简体   繁体   English

如何在 PHP 中递归地创建嵌套数组祖先

[英]How to create nested array ancestors recursively in PHP

I'm using PHP 7.3.我正在使用 PHP 7.3。 I want to create a nested array that each item must contain its own ancestors.我想创建一个嵌套数组,每个项目都必须包含自己的祖先。

Original Array:原始数组:

[
    [
        id => 1,
        parentId => ""
    ],
    [
        id => 2,
        parentId => 1
    ],
    [
        id => 3,
        parentId => 2
    ]
]

Required Array:所需数组:

[
    [
        id => 1,
        parentId => "",
        ancestors => []
    ],
    [
        id => 2,
        parentId => 1,
        ancestors => [
            [
                id => 1,
                parentId => "",
                ancestors => []
            ],
        ]
    ],
    [
        id => 3,
        parentId => 2,
        ancestors => [
                [
                    id => 1,
                    parentId => "",
                    ancestors => []
                ],
                [
                    id => 2,
                    parentId => 1,
                    ancestors => [
                        [
                            id => 1,
                            parentId => "",
                            ancestors => []
                        ],
                    ]
                ],
        ]
    ]
]

I tried to use this solution, but I think this problem is different.我尝试使用这个解决方案,但我认为这个问题是不同的。 Any help / guidance is greatly appreciated.非常感谢任何帮助/指导。 Thanks.谢谢。

You could first make use of array_column to group your entries by ID, then array_reduce to build your new array that includes ancestors (without altering the base one):您可以首先使用array_column按 ID 对条目进行分组,然后array_reduce构建包含祖先的新数组(不更改基础数组):

$entriesById = array_column($array, null, 'id');
    
$entriesWithAncestors = array_reduce(
  $entriesById,

  static function (array $result, array $entry) use ($entriesById): array {
    $result[$entry['id']] = $entry + ['ancestors' => []];
    $parentId = $entry['parentId'];
    while (isset($result[$parentId])) {
      $result[$entry['id']]['ancestors'][] = $result[$parentId];
      $parentId = $entriesById[$parentId]['parentId'] ?? null;
    }
    return $result;
  }, 

  []
);

print_r($entriesWithAncestors);

Demo演示

Note that this assumes parent entries are always present before their children in the original array, as you mentioned in the comments.请注意,这假设父条目始终出现在原始数组中的子条目之前,正如您在评论中提到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM