How can one optimize SQL queries to prevent the need for complex array manipulation in PHP?

Complex array manipulation in PHP can often be avoided by optimizing SQL queries to retrieve the data in the desired format directly. By using SQL functions like GROUP_CONCAT, GROUP BY, JOIN, and SELECT, you can shape the data in the way you need it before it even reaches your PHP code. This can reduce the need for extensive array manipulation and improve the performance of your application.

// Example SQL query using GROUP_CONCAT to retrieve data in desired format
$sql = "SELECT user_id, GROUP_CONCAT(email) AS emails
        FROM users
        GROUP BY user_id";

// Execute the query and fetch the results
$result = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

// Now $result will contain data in the format:
// [
//     ['user_id' => 1, 'emails' => 'email1,email2,email3'],
//     ['user_id' => 2, 'emails' => 'email4,email5'],
//     ...
// ]