What are the advantages of directly creating a multidimensional array from database results compared to retrieving all data and then manipulating it in PHP?

When directly creating a multidimensional array from database results, you can save memory and processing time by avoiding the need to retrieve and store all the data in PHP before manipulating it. This can be particularly beneficial when dealing with large datasets, as it reduces the amount of data that needs to be transferred between the database and the PHP script.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare and execute a query to retrieve data
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();

// Create a multidimensional array directly from database results
$data = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $data[] = $row;
}

// Now you can manipulate the $data array as needed