Created
September 16, 2015 15:30
-
-
Save tridungpham/3ff610367b6c5bab7291 to your computer and use it in GitHub Desktop.
Transform flat array into tree
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 | |
// http://php.net/manual/en/language.references.php | |
$flat = array( | |
"7" => array( | |
"id" => 7, | |
"parent" => 6 | |
), | |
"6" => array( | |
"id" => 6, | |
"parent" => 5 | |
), | |
"5" => array( | |
"id" => 5, | |
"parent" => 4 | |
), | |
"4" => array( | |
"id" => 4, | |
"parent" => 0 | |
), | |
"3" => array( | |
"id" => 7, | |
"parent" => 2 | |
), | |
"2" => array( | |
"id" => 7, | |
"parent" => 1 | |
), | |
"1" => array( | |
"id" => 7, | |
"parent" => 0 | |
) | |
); | |
# transform $flat into a tree: | |
foreach($flat as $id => &$value) | |
{ | |
# check if there is a patrent | |
if ($parentId = $value['parent']) | |
{ | |
$flat[$parentId][0][$id] =& $value; # add child to parent | |
unset($flat[$id]); # remove from topmost level | |
} | |
} | |
unset($value); # remove iterator reference | |
print_r($flat); # your tree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
StackOverflow question:
http://stackoverflow.com/questions/7730889/hierarchy-commenting-system-php