Requirements = PHP 5.3
function buildTree($flat, $pidKey, $idKey = null)
{
$grouped = array();
foreach ($flat as $sub){
$grouped[$sub[$pidKey]][] = $sub;
}
$fnBuilder = function($siblings) use (&$fnBuilder, $grouped, $idKey) {
foreach ($siblings as $k => $sibling) {
$id = $sibling[$idKey];
if(isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
$tree = $fnBuilder($grouped[0]);
return $tree;
}
Usage:
$flat = array(
array('id'=>100, 'parentID'=>0, 'name'=>'a'),
array('id'=>101, 'parentID'=>100, 'name'=>'a'),
array('id'=>102, 'parentID'=>101, 'name'=>'a'),
array('id'=>103, 'parentID'=>101, 'name'=>'a'),
);
$tree = buildTree($flat, 'parentID', 'id');
print_r($tree);