What are some best practices for efficiently sorting and arranging complex hierarchical data structures in PHP to avoid performance issues and ensure code maintainability?

Complex hierarchical data structures can be efficiently sorted and arranged in PHP by using recursive functions to traverse the hierarchy. This approach helps avoid performance issues by minimizing the number of iterations needed to organize the data. Additionally, using data structures like arrays or objects to represent the hierarchy can make the code more maintainable and easier to work with.

function sortHierarchy($data, $parentId = null) {
    $result = array();
    
    foreach ($data as $item) {
        if ($item['parent_id'] == $parentId) {
            $children = sortHierarchy($data, $item['id']);
            if (!empty($children)) {
                $item['children'] = $children;
            }
            $result[] = $item;
        }
    }
    
    return $result;
}

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

$sortedHierarchy = sortHierarchy($data);
print_r($sortedHierarchy);