In PHP, what are some strategies for optimizing code that involves nested foreach loops to process database query results?

When dealing with nested foreach loops to process database query results in PHP, one strategy for optimization is to minimize the number of queries being executed within the loops. This can be achieved by fetching all necessary data in a single query and then processing it using PHP code. Additionally, you can utilize associative arrays or objects to store and access the data efficiently, rather than repeatedly querying the database. Another approach is to consider using JOIN statements in the initial query to retrieve related data in a more efficient manner.

// Example of optimizing nested foreach loops for processing database query results

// Assume $connection is the database connection object

// Fetch all necessary data in a single query
$query = "SELECT * FROM table1 JOIN table2 ON table1.id = table2.table1_id";
$result = $connection->query($query);

// Process the query results using PHP code
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[$row['id']] = $row;
}

// Nested foreach loop to process the data efficiently
foreach ($data as $row) {
    // Process each row of data
    foreach ($row['table2'] as $subRow) {
        // Process nested data
    }
}