Build a tree from a flat array in PHP
$hello = array
(
array("ID" => "1","student" => "Jassi","marks" => "80","parent_id" => ""),
array("ID" => "2","student" => "Golu","marks" => "80","parent_id" => "1"),
array("ID" => "3","student" => "Jassi","marks" => "80","parent_id" => "1"),
array("ID" => "4","student" => "Jai","marks" => "90","parent_id" => "1"),
array("ID" => "5","student" => "Jassi","marks" => "85","parent_id" => "1"),
array("ID" => "6","student" => "Ravinder","marks" => "30","parent_id" => "1"),
array("ID" => "7","student" => "Mukesh","marks" => "45","parent_id" => "1"),
array("ID" => "8","student" => "Ankush","marks" => "96","parent_id" => "2"),
array("ID" => "9","student" => "Aman","marks" => "90","parent_id" => "2")
);
function buildTree($elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['ID']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
echo '<pre>';
$tree = buildTree($hello,1);
print_r( $tree );
Comments
Post a Comment