-
-
Save mgsmus/155e3e946036c8f18f65ed3664fdde8d to your computer and use it in GitHub Desktop.
Convert adjacency list into tree without recursion and second array.
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 | |
function array_to_tree(array $array, $parent_id = 0) | |
{ | |
$array = array_combine(array_column($array, 'id'), array_values($array)); | |
foreach ($array as $k => &$v) { | |
if (isset($array[$v['parent_id']])) { | |
$array[$v['parent_id']]['children'][$k] = &$v; | |
} | |
unset($v); | |
} | |
return array_filter($array, function($v) use ($parent_id) { | |
return $v['parent_id'] == $parent_id; | |
}); | |
} |
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 | |
/** | |
* Convert adjacency list into tree without recursion and second array. | |
* | |
* @param array $array array to convert | |
* @param int|null $parent_id start with given parent id | |
* @param string $primary_key primary key name | |
* @param string $foreign_key foreign key name | |
* @return array|null converted array | |
*/ | |
function array_to_tree(array $array, $parent_id = 0, $primary_key = 'id', $foreign_key = 'parent_id') { | |
$first_element = current($array); | |
if (!is_array($first_element)) { | |
trigger_error('array_to_tree expects parameter 1 to be a multi-dimensional array, ' . gettype($first_element) . ' given', E_USER_WARNING); | |
return null; | |
} | |
if (!array_key_exists($primary_key, $first_element)) { | |
trigger_error('array_to_tree expects child array to have a ' . $primary_key . ' key', E_USER_WARNING); | |
return null; | |
} | |
if (!array_key_exists($foreign_key, $first_element)) { | |
trigger_error('array_to_tree expects child array to have a ' . $foreign_key . ' key', E_USER_WARNING); | |
return null; | |
} | |
$keys = array_map(function($e) use ($primary_key) { | |
return $e[$primary_key]; | |
}, $array); | |
$values = array_values($array); | |
$array = array_combine($keys, $values); | |
foreach ($array as $k => &$v) { | |
if (isset($array[$v[$foreign_key]])) { | |
$array[$v[$foreign_key]]['children'][$k] = &$v; | |
} | |
unset($v); | |
} | |
return array_filter($array, function($v) use ($parent_id, $foreign_key) { | |
return $v[$foreign_key] == $parent_id; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment