【问题标题】:Buy One Get One Half Price in PHP shopping cart totalPHP购物车总价买一送一
【发布时间】:2017-04-16 12:40:53
【问题描述】:

我正在用 PHP 创建一个购物车,一个特定的项目是买一送一的半价。当用户购买该商品时,我希望从总数中扣除该报价,但我一直坚持如何在数学上做到这一点。

到目前为止,我在从数据库获取数据的 if 循环中有类似的内容:

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

那么我认为它会是这样的:

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

任何帮助表示赞赏。

【问题讨论】:

  • $total = $total+((0.5 * $arraycart['Price']) * $quantity);?
  • @u_mulder 这将增加所有东西的半价。他们已经在计算全价乘以数量。您不想在此基础上再加半价。您更有可能希望减半数量的半价,例如:$total = $total - ($arraycart['Price'] * 0.5 * floor($quantity / 2)),这将删除一半商品的半价。这当然是在您完成$total 数学之后。
  • 我只是给了一个提示。检查何时应用它是 OP 的任务
  • @u_mulder 我只提到它是因为它在技术上是错误的。如果我有 10 件东西,每件 1 美元,我不想再添加一个 0.5 * $price * $quantity 使我的总计 15 美元。如果这是循环数量并添加到总和,那么是的,为每个其他项目添加 0.5 * $price 就可以了。
  • 我会使用另一种方法来实现目标。我会将折扣放入一个单独的数组中,然后我将使用该数组来确定折扣是否仍应适用。将所有内容放在一起会使事情复杂化。

标签: php shopping-cart


【解决方案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;
?>

【讨论】:

  • 您在第一次之后给予所有商品 50% 的折扣,而不仅仅是买一送一,这意味着对于以全价购买的每件商品,下一件商品将减半。如果数量是 5,那么您将在其中 4 件上打折,而它应该只在 2 件上。
  • 在 if (and $quantity
  • 所以如果您订购 4 件,您没有折扣吗?
  • 好的意味着如果您的产品是成对的,那么原价+半价将计入,否则您将计入原价。我根据您的要求更改了上面的代码。希望它有助于理解你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 2017-09-10
相关资源
最近更新 更多