What are the potential pitfalls of using nested foreach loops in PHP when iterating over database query results?

Using nested foreach loops when iterating over database query results can lead to performance issues, especially if the result set is large. Each nested loop iteration adds to the overall complexity and can result in slower execution times. To avoid this pitfall, consider fetching all necessary data in a single query and then using PHP to organize and process the data as needed.

// Example of fetching all necessary data in a single query and then organizing it with PHP
$query = "SELECT * FROM table";
$result = $pdo->query($query);

$data = array();
foreach ($result as $row) {
    // Organize data as needed
    $data[$row['category']][] = $row['value'];
}

// Process organized data
foreach ($data as $category => $values) {
    echo "Category: $category\n";
    foreach ($values as $value) {
        echo "- $value\n";
    }
}