Skip to content

Instantly share code, notes, and snippets.

@chucktrukk
Created November 18, 2009 21:49
Show Gist options
  • Save chucktrukk/238304 to your computer and use it in GitHub Desktop.
Save chucktrukk/238304 to your computer and use it in GitHub Desktop.
<?php
function buildHierarchy(&$results, $parent = 0, $level = 0)
{
global $modx;
$children = array_values($modx->getChildIds($parent, 1));
$level = $level + 1;
foreach($children as $child)
{
$descendents = array_values($modx->getChildIds($child, 100));
array_unshift($descendents, $child);
$results[$child] = array(
'id' => $child,
'descendents' => $descendents,
'level' => $level,
);
buildHierarchy($results, $child, $level);
}
}
function buildClosureTable($results)
{
$closure_array = array();
foreach($results as $result)
{
foreach($result['descendents'] as $child)
{
$closure_array[] = array(
'ancestor' => $result['id'],
'descendent' => $child,
'level' => $results[$child]['level'],
);
}
}
return $closure_array;
}
$root = 0;
$descendents = array_values($modx->getChildIds($root, 100));
array_unshift($descendents, $root);
$results = array(0 => array(
'id' => 0,
'descendents' => $descendents,
'level' => 0,
)
);
buildHierarchy($results);
$closure_array = buildClosureTable($results);
$table_tpl = '<table cellpadding="5"><tr><th>Ancestor</th><th>Descendent</th><th>Level</th></tr>%s</table>';
$rows_tpl = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>';
$rows = '';
foreach($closure_array as $row)
{
$rows .= sprintf($rows_tpl, $row['ancestor'], $row['descendent'], $row['level']);
}
echo sprintf($table_tpl, $rows);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment