Created
September 17, 2015 05:22
-
-
Save tridungpham/e9411f89f3279667427b to your computer and use it in GitHub Desktop.
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 | |
$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