<?php
$array = [
[
'id' => 1,
'parentId' => ""
],
[
'id' => 2,
'parentId' => 1
],
[
'id' => 3,
'parentId' => 2
]
];
$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);
preferences:
26.5 ms | 406 KiB | 5 Q