Created
February 22, 2021 19:54
-
-
Save fernandojmartin/4fcbe80435b98fe504150a8665662679 to your computer and use it in GitHub Desktop.
Build a tree from collection of elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$events = [ | |
["id" => 14, "name" => 'root event', "parent_id" => 0], | |
["id" => 15, "name" => 'an event', "parent_id" => 14], | |
["id" => 33, "name" => 'a sub event', "parent_id" => 15], | |
["id" => 52, "name" => 'a sub event (2)', "parent_id" => 33], | |
["id" => 68, "name" => 'another root event', "parent_id" => 0], | |
["id" => 83, "name" => 'yet another root event', "parent_id" => 0], | |
["id" => 84, "name" => 'another sub event', "parent_id" => 83], | |
["id" => 87, "name" => 'another sub event (x)', "parent_id" => 83], | |
]; | |
function buildDataTree(array &$elements, $parentId = 0): array | |
{ | |
$branch = []; | |
foreach ($elements as $element) { | |
if ($element['parent_id'] === $parentId) { | |
$children = buildDataTree($elements, $element['id']); | |
if ($children) { | |
$element['children'] = $children; | |
} | |
$branch[$element['id']] = $element; | |
unset($elements[$element['id']]); | |
} | |
} | |
return $branch; | |
} | |
$tree = buildDataTree($events); | |
function buildVisualTree($tree, $level = 0) | |
{ | |
$options = ''; | |
foreach ($tree as $event) { | |
$pad = '·'; | |
$line = "{$event['id']}: {$event['name']} ({$event['parent_id']})"; | |
$options.= str_repeat($pad, 2 * $level). $line . PHP_EOL; | |
if (isset($event['children'])) { | |
$options .= buildVisualTree($event['children'], ++$level); | |
$level = 0; | |
} | |
} | |
return $options; | |
} | |
echo buildVisualTree($tree); | |
// 14: root event (0) | |
// ··15: an event (14) | |
// ····33: a sub event (15) | |
// ······52: a sub event (2) (33) | |
// 68: another root event (0) | |
// 83: yet another root event (0) | |
// ··84: another sub event (83) | |
// ··87: another sub event (x) (83) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given a collection of elements with an
id
and aparent_id
, sort them as a tree (array) and then build a string out of them to print out.The padding char can be replaced to whatever you may need.
# (id): name (parent_id) 14: root event (0) ··15: an event (14) ····33: a sub event (15) ······52: a sub event (2) (33) 68: another root event (0) 83: yet another root event (0) ··84: another sub event (83) ··87: another sub event (x) (83)