Skip to content

Instantly share code, notes, and snippets.

@devuo
Created October 24, 2013 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devuo/7145604 to your computer and use it in GitHub Desktop.
Save devuo/7145604 to your computer and use it in GitHub Desktop.
Tree Equalizer
<?php
$tree = array(
'a' => array(
'title' => 'The Big A',
'children' => array(
'a1' => array(
'title' => 'The Lesser A1'
),
'a2' => array(
'title' => 'The Interesting A2'
),
),
),
'b' => array(
'title' => 'The Independent B'
),
'c' => array(
'title' => 'The Massive C',
'children' => array(
'c1' => array(
'title' => 'The Cool C1',
'children' => array(
'c11' => array(
'title' => 'The Awesome C11',
),
'c12' => array(
'title' => 'The Awesome C11',
),
'c13' => array(
'title' => 'The Awesome C11',
),
),
),
'c2' => array(
'title' => 'The Awesome C11',
),
),
),
);
// Execution
// ----------------------------------------------------------------------------
$depth = depth($tree);
$levels = array();
$table = deepen($tree, $depth, $levels);
$bottom = array_keys($levels[count($levels) - 1]);
print $depth . "\n";
print_r($table);
print_r($levels);
print_r($bottom);
// Helpers
// ----------------------------------------------------------------------------
/**
* Recursively finds the max level in a given tree structure.
*/
function depth($branches, $depth = 0) {
foreach($branches as $branch) {
if (!empty($branch['children'])) {
$detected = depth($branch['children'], $depth + 1);
if ($detected > $depth) {
$depth = $detected;
}
}
}
return $depth;
}
/**
* Deepens the tree branches until all have the same depth with empty twigs.
*/
function deepen($branches, $max_level, &$levels = array(), $current_level = 0) {
if ($current_level < $max_level) {
foreach($branches as $key => &$branch) {
$levels[$current_level][$key] = $branch;
if (empty($branch['children'])) {
$branch['children'] = array(
$key => twig()
);
}
$branch['children'] = deepen($branch['children'], $max_level, $levels, $current_level + 1);
}
}
return $branches;
}
/**
* An empty tree branch twig.
*/
function twig() {
return array(
'title' => ''
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment