现有一个需求:
根据城市,根据距离的远近计算价格,
比如在郑州:2公里以内7元,3公里以内10元,5公里以内13元 ,5~10公里,超过部分每公里加2元 10公里以上加3元
1公里 7元
2公里 7元
2.5公里 10元
3公里10元
3.5公里 13元
6公里 15元 13+(6-5)*2
15公里 13+ (10-5)*2 + (15-10)*3
步骤:
1 根据城市获得当前城市的计费规则
2 根据规则计算价格
配置:
2:7:1,3:10:1,5:13:1,10:2:2,10:3:3
第三个参数 1 表示定值,2表示超出加价值,3表示 超出某个距离以后加价值,一般都是最后的,必选项
2公里以内7元,3公里以内10元,5公里以内13元 ,5~10公里,超过部分每公里加2元 10公里以上加3元
根据城市获得配置后 (这里需要把配置组成数组。)
public static function getPriceRule($citycode)
{
$price_rule = Config::getValue('price', $citycode);
$rule_arr = explode(',', $price_rule);
$rule = [];
foreach ($rule_arr as $key => $val) {
$val_arr = explode(':', $val);
$rule[$key]['distance'] = $val_arr[0];
$rule[$key]['price'] = $val_arr[1];
$rule[$key]['type'] = $val_arr[2];
}
$rule = arrSort($rule, ['direction' => 'SORT_ASC', 'field' => 'distance']);
return $rule;
}
/**
* 根据配置 计算价格
*/
public static function getPrice($citycode, $distance)
{
$rule = self::getPriceRule($citycode);
$sum = 0;
for ($i = 0; $i <= count($rule) - 1; $i++) {
$now_type = $rule[$i]['type'];
$now_price = $rule[$i]['price'];
$now_distance = $rule[$i]['distance'];
if ($i == 0) {
$pre_distance = 0;
} else {
$pre_distance = $rule[$i - 1]['distance'];
}
if ($distance <= $now_distance) {
if ($now_type == 1) {
$sum = $now_price;
} else {
$sum += ($distance - $pre_distance) * $now_price;
}
return $sum;
} else {
if ($now_type == 1) {
$sum = $now_price;
} else if ($now_type == 2) {
$sum += ($now_distance - $pre_distance) * $now_price;
} else {
$sum += ($distance - $pre_distance) * $now_price;
}
}
}
return $sum;
}
上一篇: php 区分 移动设备,浏览器信息
下一篇: ThinkCMF 配置到服务器 一直返回500