PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php function distributeDiscount($products, $discountAmount) { // Calculate the base discount amount for each product $numProducts = count($products); $baseDiscount = $discountAmount / $numProducts; // Initialize the total discount $totalDiscount = 0; // Loop through each product except the last one for ($i = 0; $i < $numProducts - 1; $i++) { $product = $products[$i]; $product['discount'] = $baseDiscount; $totalDiscount += $baseDiscount; } // Calculate the discount for the last product $lastProduct = $products[$numProducts - 1]; $lastProductDiscount = $discountAmount - $totalDiscount; $lastProduct['discount'] = $lastProductDiscount; // Return the updated array of products return $products; } // Example usage: $products = [ ['name' => 'Product A', 'price' => 100], ['name' => 'Product B', 'price' => 50], ['name' => 'Product C', 'price' => 30], ]; $discountAmount = 70; $productsWithDiscounts = distributeDiscount($products, $discountAmount); // Print the updated array of products with discounts print_r($productsWithDiscounts);
Show:  
Copy Clear