How can one efficiently retrieve data from a database to directly build a multidimensional array with a hierarchical structure in PHP?

To efficiently retrieve data from a database to directly build a multidimensional array with a hierarchical structure in PHP, you can use a recursive function to fetch the data and construct the array. This approach allows you to build the array in a nested manner based on the hierarchical relationships in the database table.

function buildHierarchy($parent_id = 0) {
    $result = array();
    
    // Retrieve data from the database based on the parent_id
    $query = "SELECT * FROM your_table WHERE parent_id = $parent_id";
    $data = // Execute query and fetch data
    
    foreach ($data as $row) {
        $result[$row['id']] = array(
            'id' => $row['id'],
            'name' => $row['name'],
            'children' => buildHierarchy($row['id']) // Recursively build children
        );
    }
    
    return $result;
}

// Call the function to build the hierarchical array
$hierarchy = buildHierarchy();