Skip to content

Instantly share code, notes, and snippets.

@tridungpham
Created September 17, 2015 05:22
Show Gist options
  • Save tridungpham/e9411f89f3279667427b to your computer and use it in GitHub Desktop.
Save tridungpham/e9411f89f3279667427b to your computer and use it in GitHub Desktop.
<?php
$comments = [
1 => ['content' => "The first comment", 'parent' => 0],
2 => ['content' => "The second comment", 'parent' => 0],
3 => ['content' => "Reply of first comment", 'parent' => 1],
4 => ['content' => "Another reply of first comemnt", 'parent' => 1],
5 => ['content' => "Reply of a reply of the first comment", 'parent' => 4]
];
function mapTree($dataset) {
$tree = array();
foreach ($dataset as $id=>&$node) {
if ($node['parent'] === null) { // root node
$tree[$id] = &$node;
} else { // sub node
$dataset[$node['parent']]['children'][$id] = &$node;
}
}
return $tree;
}
var_dump(mapTree($comments));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment