基于数量的价格计算器 [英] Price Calculator based on Quantity

查看:59
本文介绍了基于数量的价格计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的脚本以添加到我的html网站。

I am trying to create a simple script to add to my html website.

我需要它根据用户输入的数量来计算价格。

I need it to calculate the price based on the quantity the user inputs.

例如,值1-1000乘以1.50并显示,1001-5000乘以1.20并显示,5001-10000乘以1并显示,并且任意数字上面将显示一条错误消息,如必须低于10000。

For example, a value of 1-1000 will be multiplied by 1.50 and displayed, 1001-5000 multiplied by 1.20 and displayed, 5001-10000 multiplied by 1 and displayed and any number above that would display an error message like "Must be below 10000".

我一直试图在php中完成此操作,但未成功。

I've been trying to do this in php with no success.

推荐答案

您可能会发现操作员开关非常有用(切换到PHP )。像这样的东西:

You may find operator switch very useful (Switch in PHP). Something like this:

...
switch ($quantity) {
    case (($quantity >= 1) && ($quantity <= 1000)):
        $multiplicator = 1.5;
        echo $quantity * $multiplicator;
        break;
    case (($quantity >= 1001) && ($quantity <= 5000)):
        $multiplicator = 1.2;
        echo $quantity * $multiplicator;
        break;
    case (($quantity >= 5001) && ($quantity <= 10000)):
        $multiplicator = 1.2;
        echo $quantity * $multiplicator;
        break;
    case ($quantity > 10000):
        echo 'Quantity must be less then 10000!';
        break;
}
....

编辑:使用循环的另一种选择:

Edited: another option using loop:

...
$limits_array = array(
    0 => array(
        'min' => 1,
        'max' => 1000,
        'mul' => 1.5,
    ),
    1 => array(
        'min' => 1001,
        'max' => 5000,
        'mul' => 1.2,
    ),
    2 => array(
        'min' => 5001,
        'max' => 10000,
        'mul' => 1,
    ),
);
foreach ($limits_array as $limits)
    if (($quantity >= $limits['min']) && ($quantity <= $limits['max']) {
        echo $quantity * $limits['mul'];
        break;
    }
if ($quantity > $limits['max'])
    echo 'Quantity must be less then 10000!';
...

请注意,在foreach最后一个值元素($ value是它的通用名称,存在$ limits)之后,仍然存储数组中的最后一项。请看一下方括号。

Please notice, that after foreach last value element ($value is a common name for it, there it is $limits) still stores the last item from array. Take a look at brackets.

这篇关于基于数量的价格计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆