How can one optimize PHP code to handle data manipulation and array creation based on SQL query results efficiently?

To optimize PHP code for handling data manipulation and array creation based on SQL query results efficiently, you can use the fetchAll() method to retrieve all rows at once and then loop through the results to manipulate the data and create arrays as needed. This approach reduces the number of database queries and improves performance.

// Assuming $pdo is your PDO object and $sqlQuery is your SQL query

// Execute the SQL query
$stmt = $pdo->query($sqlQuery);

// Fetch all rows at once
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store manipulated data
$manipulatedData = [];

// Loop through the results to manipulate data and create arrays
foreach ($results as $row) {
    // Manipulate data here
    $manipulatedData[] = [
        'column1' => $row['column1'],
        'column2' => $row['column2'],
        // Add more columns as needed
    ];
}

// Use $manipulatedData array as needed