What are the best practices for querying and displaying hierarchical data in PHP?
When querying and displaying hierarchical data in PHP, it is important to use recursive functions to traverse the tree structure efficiently. One common approach is to store hierarchical data in a database table with columns for the node ID and parent ID. By using recursive functions to fetch and display the data, you can easily navigate through the hierarchy and display it in a structured manner.
function displayHierarchy($parent_id, $level = 0) {
// Fetch data from the database based on the parent ID
$result = query("SELECT * FROM hierarchy_table WHERE parent_id = $parent_id");
// Display each node at the current level
foreach($result as $row) {
echo str_repeat('-', $level) . $row['node_name'] . "<br>";
// Recursively call the function for child nodes
displayHierarchy($row['node_id'], $level + 1);
}
}
// Start displaying the hierarchy from the root node
displayHierarchy(0);