What are the best practices for organizing and managing complex arrays in PHP, especially when dealing with related data from a database?

Organizing and managing complex arrays in PHP, especially when dealing with related data from a database, can be challenging. One best practice is to use associative arrays to structure the data in a logical way, such as using keys to represent relationships between different pieces of data. Another approach is to break down the data into smaller, more manageable arrays or objects to make it easier to work with. Additionally, utilizing functions like array_map or array_filter can help manipulate and filter the data efficiently.

// Example of organizing and managing complex arrays in PHP

// Sample data from a database
$dataFromDatabase = [
    ['id' => 1, 'name' => 'John Doe', 'age' => 30, 'department' => 'HR'],
    ['id' => 2, 'name' => 'Jane Smith', 'age' => 25, 'department' => 'IT'],
    ['id' => 3, 'name' => 'Alice Johnson', 'age' => 35, 'department' => 'Finance']
];

// Organizing the data into an associative array
$organizedData = [];
foreach ($dataFromDatabase as $row) {
    $organizedData[$row['id']] = [
        'name' => $row['name'],
        'age' => $row['age'],
        'department' => $row['department']
    ];
}

// Output the organized data
print_r($organizedData);