Skip to content

Instantly share code, notes, and snippets.

@b-b3rn4rd
Last active March 28, 2018 19:06
Show Gist options
  • Save b-b3rn4rd/8797363 to your computer and use it in GitHub Desktop.
Save b-b3rn4rd/8797363 to your computer and use it in GitHub Desktop.
Convert adjacency list into tree without recursion and second array.
<?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;
});
}
<?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;
});
}
@b-b3rn4rd
Copy link
Author

if PHP < 5.5

@amacado
Copy link

amacado commented Jul 16, 2016

Thank you. Saved me lot of time! :)

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