What are best practices for handling data retrieval from parent-child relationships in PHP?

When retrieving data from parent-child relationships in PHP, it is best practice to use recursive functions to handle the hierarchical structure. This allows for easy traversal of the data and ensures that all levels of the relationship are properly accessed.

function getChildren($parent_id, $data) {
    $children = array();
    
    foreach ($data as $item) {
        if ($item['parent_id'] == $parent_id) {
            $item['children'] = getChildren($item['id'], $data);
            $children[] = $item;
        }
    }
    
    return $children;
}

// Example usage
$data = [
    ['id' => 1, 'parent_id' => null, 'name' => 'Parent 1'],
    ['id' => 2, 'parent_id' => 1, 'name' => 'Child 1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'Child 2'],
    ['id' => 4, 'parent_id' => 2, 'name' => 'Grandchild 1'],
];

$parent_id = null;
$tree = getChildren($parent_id, $data);

print_r($tree);