PHP增量价格计算器基于数量

时间:2014-11-26 21:27:12

标签: php mysql inventory

我正在尝试编写一个根据数量计算价格的脚本。

数据库:
pid | prodict |单位|价钱
1 |可乐| 100 | 2
2 |可乐| 100 | 1.8
3 |可乐| 300 | 1.5
4 |焦炭| | 1.1
1 |百事可乐| 100 | 2.2
2 |百事可乐| 50 | 2
3 |百事| | 0.8

Pid是产品ID,产品是产品名称/产品代码。 单位为增量单位,或者除了现有单位的数量,价格是增量单位的每单位价格。

真正的问题:

  • 如果单位是''或Null,那就是标识最大累积单位,然后该空列中的价格适用于该单位。
  • 并非所有产品都具有相同的价格水平。有些人可能会得到1个值(统一费率,在这种情况下,单位将为空或'。有些可能会尽可能地增加。
  • 没有累积列,我无法添加。它不存在,并且现在不可能添加,因为产品可能是数百万(假设,使代码灵活的无限产品)
  • 所有你得到的是一个单位和产品代码。例如。 100单位焦炭,或200单位百事可乐。
  • 单位列中的数字是包含的,即小于等于。

我是For循环和破坏(糟糕的编程)的忠实粉丝,但现在我认为我需要条件或while循环,因为我没有太多信心。

提前谢谢

注意如果您觉得难以理解问题,那么只需假设所得税计算器,相同或类似的东西 - 高达x金额,基本税,然后是下一个y金额,y税率,下一个z金额,z税率超过z,z +税

1 个答案:

答案 0 :(得分:0)

嗯,您当然希望首先循环使用这些产品,然后根据传入的数量计算总数。这样的东西?

// Using PostgreSQL as an example here
$entries = pg_fetch_all(pg_query('SELECT * FROM database ORDER BY prodict, pid ASC'));

// Have the quantities ready;
$quantities = array(
    'coke' => 1024,
    'pepsi' => 512,
);

// Prepare an array to hold the total values.
$totals = array();

// Loop through the entries in the array in a non-conventional way
while($entry = current($entries)) {
    // Get the name of the product from the array
    $product = $entry['prodict'];
    // And the quantity
    $quantity = $quantities[$product];
    // Prepare a price for this product starting at zero
    $price = 0;
    // Now use a do-while to figure out the price
    do {
        // At this point '$entry' contains information about the pricing for the first 'x' quanitity
        $quantityAtThisPrice = $entry['unit'];
        // Check the price
        $priceForThisUnit = $entry['price'];
        // Check we have any quantity remaining of this product
        if($quantity > 0) {
            // Check if the quantity at this price is null or if that quantity at this price is more than what we have left
            if($quantityAtThisPrice === null || $quantityAtThisPrice > $quantity) {
                // This means the rest of the quantity is at this price
                $price += ($quantity * $priceForThisUnit);
                // No more quantity left to price
                $quantity = 0;
            }
            // Otherwise we'll add for this unit, and move on to the next
            else {
                // Add to the price
                $price += ($quantityAtThisPrice * $priceForThisUnit);
                // Subtract the quantity we just priced
                $quantity -= $quantityAtThisPrice;
            }
        }
        // Now fetch the next entry
        $entry = next($entries);
    } while ($entry['prodict'] === $product);

    // Add the calculated price to the totals array
    $totals[$product] = $price;
}

var_dump($totals);

有点被带走但我觉得应该有用。

相关问题