How can PHP loops be optimized when constructing JSON output from MySQL queries?

When constructing JSON output from MySQL queries in PHP, loops can be optimized by fetching all the rows at once using the fetchAll() method instead of fetching them one by one. This reduces the number of database calls and improves performance.

// Fetch all rows from the MySQL query result at once
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the JSON output
$json_output = [];

// Loop through the fetched rows and add them to the JSON output array
foreach ($rows as $row) {
    $json_output[] = $row;
}

// Encode the JSON output array into a JSON string
$json_string = json_encode($json_output);

// Output the JSON string
echo $json_string;