Buy One Get One Half Price in PHP shopping cart total

不想你离开。 提交于 2019-12-24 07:56:55

问题


I am creating a shopping cart in PHP and a particular item is buy one get one half price. When the user purchases the item, I would get like the offer to be deducted from the total but I'm stuck on how I would do this mathematically.

So far I have something like this in a if loop getting data from database:

$total = $total+($arraycart['Price']*$quantity);

Then I think it will be something along the lines of:

if ($arraycart['Item'] == "A1" and $quantity > 1) {
//calculate here buy one get one half price
}

Any help appreciated.


回答1:


<?php
$total = 0;
$arraycart['Price'] = 10;
$arraycart['Item'] = 'A1';

$quantity = 3; // change item quantity here

if ($arraycart['Item'] == "A1" and $quantity % 2 == 0 ) {
    //calculate here buy one get one half price
    $real = ($quantity/2)*$arraycart['Price'];
    $half = ($quantity/2)*($arraycart['Price']/2);

    $total = $real+$half;

} else {
    $quantity = $quantity-1;

    $real = ($quantity/2)*$arraycart['Price'];
    $half = ($quantity/2)*($arraycart['Price']/2);

    $total = $real+$half+$arraycart['Price'];

}

echo $total;
?>


来源:https://stackoverflow.com/questions/40918048/buy-one-get-one-half-price-in-php-shopping-cart-total

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!