Skip to content

Instantly share code, notes, and snippets.

@tridungpham
Created September 16, 2015 15:30
Show Gist options
  • Save tridungpham/3ff610367b6c5bab7291 to your computer and use it in GitHub Desktop.
Save tridungpham/3ff610367b6c5bab7291 to your computer and use it in GitHub Desktop.
Transform flat array into tree
<?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
@tridungpham
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment