Skip to main content

How to build a tree from a flat array in PHP>

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

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...