<?php
/**
* This function should be efficient for large sets.
* It loops a maximum of 3n times, each pass is cheap,
* and it can work with multiple levels of children,
* parents and grandparents.
*/
function makeHierarchical($flatListOfObjects) {
// Create new reference list keyed on "id",
// assuming "id" is a positive integer.
$idList = array();
foreach ($flatListOfObjects as $o) {
$idList[$o->id] = $o;
}
// Connect children with their parents, but don't remove
// them from top level yet, because they themselves might
// also be parents with children to be attached.
foreach ($idList as $o) {
if ($o->parent > 0) {
// Add as a child item to the children list of the parent.
$idList[$o->parent]->children[] = $o;
}
}
// Remove children from top level of the list.
foreach ($idList as $key => $o) {
if ($o->parent > 0) {
unset($idList[$key]);
}
}
// Return our newly created hierarchical list.
return $idList;
}
/**
* Test Functions
*/
function test_makeHierarchical() {
function makeObj($id, $name, $parent=0) {
$o = new stdClass();
$o->id = $id;
$o->name = $name;
$o->parent = $parent;
return $o;
}
$flatList[] = makeObj(1, 'Parent1');
$flatList[] = makeObj(7, 'Child1', 1);
$flatList[] = makeObj(9, 'Child2', 1);
$flatList[] = makeObj(2, 'Parent2');
$flatList[] = makeObj(88, 'Childof2', 2);
print_r($flatList);
$newList = makeHierarchical($flatList);
print_r($newList);
}
test_makeHierarchical();
?>