-
-
Save nzuwera/fd2cf09e8d82ab73f45e8d1d8e177dce to your computer and use it in GitHub Desktop.
EasyTree php tree build algorithm
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 | |
/** | |
* 1. This Algorithm can help you build tree as a nested php array from array like ('id' => x, 'parent_id' => y) | |
* 2. Algorithm speed = {O(n log n) + О(N)} | |
*/ | |
class EasyTree | |
{ | |
public static | |
$idKeyName = 'id', $parentIdKeyName = 'parent_id', $childrenKeyName = 'children'; | |
protected static function operator($a, $b) | |
{ | |
return ($a[self::$parentIdKeyName] === $b[self::$parentIdKeyName]) ? | |
0 : (($a[self::$parentIdKeyName] < $b[self::$parentIdKeyName]) ? -1 : 1); | |
} | |
/** | |
* @return array | |
*/ | |
public static function build(array $a) | |
{ | |
$tree = $links = array(); | |
usort($a, "self::operator"); | |
$acmeId = $a[0][self::$parentIdKeyName]; | |
for ($n = count($a), $i = 0; $i < $n; $i++) | |
{ | |
$id = $a[$i][self::$idKeyName]; | |
$parentId = $a[$i][self::$parentIdKeyName]; | |
if ($parentId === $acmeId) | |
{ | |
$tree[$id] = $a[$i]; | |
$links[$id] = &$tree[$id]; | |
} | |
else | |
{ | |
if (!isset($links[$parentId][self::$childrenKeyName])) | |
$links[$parentId][self::$childrenKeyName] = array(); | |
$links[$parentId][self::$childrenKeyName][$id] = $a[$i]; | |
$links[$id] = &$links[$parentId][self::$childrenKeyName][$id]; | |
} | |
} | |
return $tree; | |
} | |
} | |
/* | |
print_r( | |
EasyTree::build(array( | |
array('id' => 1, 'parent_id' => 0), | |
array('id' => 3, 'parent_id' => 1), | |
array('id' => 2, 'parent_id' => 1), | |
array('id' => 8, 'parent_id' => 0), | |
array('id' => 4, 'parent_id' => 0), | |
array('id' => 5, 'parent_id' => 0), | |
array('id' => 6, 'parent_id' => 0), | |
array('id' => 7, 'parent_id' => 0), | |
array('id' => 11, 'parent_id' => 7), | |
array('id' => 9, 'parent_id' => 0), | |
array('id' => 10, 'parent_id' => 7), | |
array('id' => 12, 'parent_id' => 7), | |
array('id' => 13, 'parent_id' => 7), | |
array('id' => 14, 'parent_id' => 10), | |
array('id' => 15, 'parent_id' => 10), | |
array('id' => 16, 'parent_id' => 15), | |
array('id' => 17, 'parent_id' => 16), | |
array('id' => 18, 'parent_id' => 17), | |
)) | |
); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment