Building Multi Level Menu Dynamically with PDO in PHP

id | nameOfPerson | parent
3 | John | NULL
4 | Michel | 3
5 | Husam | 4
6 | Khalaf | 5
7 | Mark | 5

and i want to display it in list like this

John
    Michel
        Husam
            Khalaf
            Mark

but in my code he just displayed

John
    Michel

How i want to Displeyed all data according to parent like above list ?

this is my function whats the wrongs ?

  public function familyTree(){
    $query = "SELECT id, nameOfPerson, parent FROM person WHERE parent is null";
    $statment = $this->db->prepare($query);
    $statment->execute();
    echo '<ul id ="family">';
    while($family = $statment->fetch(PDO::FETCH_OBJ)){
        echo '<li>'. $family->nameOfPerson;
        $query1 = "SELECT id, nameOfPerson, parent FROM person WHERE parent = :id";
        $statment1 = $this->db->prepare($query1);
       $statment1->bindValue('id', $family->id);
        $statment1->execute();
        if($statment1->rowCount() > 0){
        echo '<ul>';
        while($family2 = $statment1->fetch(PDO::FETCH_OBJ)){
            echo '<li>' . $family2->nameOfPerson . '</li>';
        }
            echo '</ul>';
        }
            echo '</li>';
    }
            echo '</ul>';      

}
// Result set from database
$arr = [
        ['id' => 3, 'name' => 'Person3', 'parent' => NULL],
        ['id' => 4, 'name' => 'Person4', 'parent' => 3],
        ['id' => 5, 'name' => 'Person5', 'parent' => 4],
        ['id' => 6, 'name' => 'Person6', 'parent' => 5],
        ['id' => 7, 'name' => 'Person7', 'parent' => 5],
        ['id' => 8, 'name' => 'Person8', 'parent' => NULL],
        ['id' => 9, 'name' => 'Person9', 'parent' => 8],
        ['id' => 10, 'name' => 'Person10', 'parent' => 8]
];

// Function to build hierarchy tree
function hierarchy($array, $parent = 0, $level = 0) {
    $tree = '<ul>';
    foreach ($array as $k => $a) {
        if ($array[$k]['parent'] === NULL) $array[$k]['parent'] = 0;
        if ($array[$k]['parent'] === $parent) {
            $tree .= '<li>';
            $tree .= $array[$k]['name'];
            $tree .= hierarchy($array, $array[$k]['id'], $level+1);
            $tree .= '</li>';
        }
    }
    $tree .= '</ul>';
    return $tree;
}

// Print hierarchy
echo hierarchy($arr);
1 Like

Here is a little bit more clean version of the function without array keys…maybe

// Function to build hierarchy tree
function hierarchy($array, $parent = 0, $level = 0) {
    $tree = '<ul>';
    foreach ($array as $v) {
        if ($v['parent'] === NULL) $v['parent'] = 0;
        if ($v['parent'] === $parent) {
            $tree .= '<li>';
            $tree .= $v['name'];
            $tree .= hierarchy($array, $v['id'], $level+1);
            $tree .= '</li>';
        }
    }
    $tree .= '</ul>';
    return $tree;
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.