【问题标题】:How to create nested array ancestors recursively in PHP如何在 PHP 中递归地创建嵌套数组祖先
【发布时间】:2020-11-29 03:01:08
【问题描述】:

我使用的是 PHP 7.3。 我想创建一个嵌套数组,每个项都必须包含自己的祖先。

原始数组:

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

必需的数组:

[
    [
        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 => []
                        ],
                    ]
                ],
        ]
    ]
]

我尝试使用this 解决方案,但我认为这个问题是不同的。 非常感谢任何帮助/指导! 谢谢。

【问题讨论】:

标签: php arrays recursion nested


【解决方案1】:

您可以先使用 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

请注意,这假设在原始数组中父条目始终出现在其子条目之前,正如您在 cmets 中提到的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2020-06-26
    相关资源
    最近更新 更多