| 1 |
<?php
|
| 2 |
// $Id:$
|
| 3 |
|
| 4 |
/**
|
| 5 |
* @file
|
| 6 |
* Miscelleneous helper functions.
|
| 7 |
*/
|
| 8 |
|
| 9 |
/**
|
| 10 |
* Recursive function, converts a flat hierarchy array with
|
| 11 |
* (id => parent_id) into a nested array.
|
| 12 |
*
|
| 13 |
*
|
| 14 |
* @param array $hierarchy
|
| 15 |
* hierarchy definition in the format array(id => parent_id, id => parent_id, ...)
|
| 16 |
* @param array $this_level Array of present level of hierarchy.
|
| 17 |
* @return nested array of hierarchy in present level.
|
| 18 |
*/
|
| 19 |
function mtk_nest_hierarchy($hierarchy, $this_level = NULL) {
|
| 20 |
// If no level is passed in, get top level hierarchy.
|
| 21 |
if (!$this_level) {
|
| 22 |
$this_level = _mtk_get_level($hierarchy, 0);
|
| 23 |
}
|
| 24 |
foreach ($this_level as $id) {
|
| 25 |
$this_level[$id] = _mtk_get_level($hierarchy, $id);
|
| 26 |
if (count($this_level[$id])) {
|
| 27 |
$this_level[$id] = mtk_nest_hierarchy($hierarchy, $this_level[$id]);
|
| 28 |
}
|
| 29 |
}
|
| 30 |
return $this_level;
|
| 31 |
}
|
| 32 |
|
| 33 |
/**
|
| 34 |
* Get a list of ids with the given parent id.
|
| 35 |
* Helper for mtk_nest_hierarchy();
|
| 36 |
*/
|
| 37 |
function _mtk_get_level($hierarchy, $parent_id = 0) {
|
| 38 |
$result = array();
|
| 39 |
foreach ($hierarchy as $id => $parent) {
|
| 40 |
if ($parent == $parent_id && $id) {
|
| 41 |
$result[$id] = $id;
|
| 42 |
}
|
| 43 |
}
|
| 44 |
return $result;
|
| 45 |
}
|