Skip to content

Instantly share code, notes, and snippets.

@ssddanbrown
Last active October 5, 2022 11:10
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 ssddanbrown/c90649e1420bce2ffd0a08b82173fa61 to your computer and use it in GitHub Desktop.
Save ssddanbrown/c90649e1420bce2ffd0a08b82173fa61 to your computer and use it in GitHub Desktop.
PHP array tree task
{
"name": "A",
"parent": null,
"id": 1,
"children": [
{
"name": "B",
"parent": "1",
"id": 2,
"children": [
{
"name": "B1",
"parent": "2",
"id": 3,
"children": [
{
"name": "B2",
"parent": "3",
"id": 4,
"children": [
{
"name": "B3",
"parent": "4",
"id": 5,
"children": []
}
]
}
]
}
]
},
{
"name": "C",
"parent": "1",
"id": 6,
"children": [
{
"name": "C1",
"parent": "6",
"id": 7,
"children": [
{
"name": "C2",
"parent": "7",
"id": 8,
"children": [
{
"name": "C3",
"parent": "8",
"id": 9,
"children": []
}
]
}
]
}
]
}
]
}
<?php
// Example single fork
$data = [
//Top of Tree
[
"name" => "A",
"parent" => null,
"id" => 1,
],
//B Branch
[
"name" => "B",
"parent" => "1",
"id" => 2,
],
[
"name" => "B1",
"parent" => "2",
"id" => 3,
],
[
"name" => "B2",
"parent" => "3",
"id" => 4,
],
[
"name" => "B3",
"parent" => "4",
"id" => 5,
],
//C Branch
[
"name" => "C",
"parent" => "1",
"id" => 6,
],
[
"name" => "C1",
"parent" => "6",
"id" => 7,
],
[
"name" => "C2",
"parent" => "7",
"id" => 8,
],
[
"name" => "C3",
"parent" => "8",
"id" => 9,
],
];
function buildTree(array $items): ?array {
// Get a mapping of each item by ID, and pre-prepare the "children" property.
$idMap = [];
foreach ($items as $item) {
$idMap[$item['id']] = $item;
$idMap[$item['id']]['children'] = [];
}
// Store a reference to the treetop if we come across it.
$treeTop = null;
// Map items to their parent's children array.
foreach ($idMap as $id => $item) {
if ($item['parent'] && isset($idMap[intval($item['parent'])])) {
$parent = &$idMap[intval($item['parent'])];
$parent['children'][] = &$idMap[$id];
} else if ($item['parent'] === null) {
$treeTop = &$idMap[$id];
}
}
return $treeTop;
}
//echo json_encode($data, JSON_PRETTY_PRINT);
echo json_encode(buildTree($data), JSON_PRETTY_PRINT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment