What are the best practices for sending separate email notifications to different companies based on items in a shopping cart in PHP?
When a user adds items to their shopping cart on an e-commerce website, it may be necessary to send separate email notifications to different companies based on the items in the cart. This can be achieved by first determining which items belong to each company, and then sending a separate email notification to each company with the relevant items listed. This can be done by iterating through the items in the cart and organizing them based on the company they belong to, and then sending separate emails using PHP's mail function.
// Assuming $cartItems is an array containing the items in the shopping cart
// Separate items by company
$companyItems = [];
foreach ($cartItems as $item) {
$company = $item['company'];
if (!isset($companyItems[$company])) {
$companyItems[$company] = [];
}
$companyItems[$company][] = $item;
}
// Send email notifications to each company
foreach ($companyItems as $company => $items) {
$to = 'company@example.com'; // Replace with the company's email address
$subject = 'Items in shopping cart';
$message = 'Items in your shopping cart:' . PHP_EOL;
foreach ($items as $item) {
$message .= $item['name'] . ' - ' . $item['quantity'] . ' x $' . $item['price'] . PHP_EOL;
}
$headers = 'From: your@example.com' . PHP_EOL;
mail($to, $subject, $message, $headers);
}