Skip to content

Instantly share code, notes, and snippets.

@alexpts
Last active September 4, 2020 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpts/99e1da6413de435fec1ae3ed7701826f to your computer and use it in GitHub Desktop.
Save alexpts/99e1da6413de435fec1ae3ed7701826f to your computer and use it in GitHub Desktop.
Flat To Tree
<?php
$flat = [
['id' => 1, 'parentId' => 0],
['id' => 2, 'parentId' => 0],
['id' => 3, 'parentId' => 1],
['id' => 4, 'parentId' => 1],
['id' => 5, 'parentId' => 2],
['id' => 6, 'parentId' => 2],
['id' => 7, 'parentId' => 3],
['id' => 8, 'parentId' => 0],
];
$expected = [
1 => ['id' => 1, 'parentId' => 0, 'child' => [
['id' => 3, 'parentId' => 1, 'child' => [
['id' => 7, 'parentId' => 3],
]],
['id' => 4, 'parentId' => 1],
]],
2 => ['id' => 2, 'parentId' => 0, 'child' => [
['id' => 5, 'parentId' => 2],
['id' => 6, 'parentId' => 2],
]],
8 => ['id' => 8, 'parentId' => 0],
];
class FlatToTree
{
public function convertArray(array $data): array
{
$map = [];
foreach ($data as $item) {
$map[$item['id']] = $item;
}
foreach ($map as &$item) {
$parentId = $item['parentId'] ?? 0;
if ($parentId !== 0) {
$map[$parentId]['child'][] = &$item;
}
}
return array_filter($map, fn(array $item): bool => $item['parentId'] === 0);
}
}
$service = new FlatToTree();
$result = $service->convertArray($flat);
echo print_r($result, true) === print_r($expected, true) ? 'ok' : 'not ok';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment