效果如下图
图一
图二
<?php
/**
*
*/
class Goods
{
/**
* @brief 计算商品的价格区间
* @param $min 最小价格
* @param $max 最大价格
* @param $showPriceNum 展示分组最大数量
* @return array 价格区间分组
*/
public function getGoodsPrice($min,$max,$showPriceNum = 5){
$goodsPrice = array("min" => $min,"max" => $max);
if($goodsPrice['min'] == null && $goodsPrice['max'] == null)
{
return array();
}
//计算商品价格区间
$perPrice = ceil(($goodsPrice['max']-$goodsPrice['min'])/$showPriceNum);
//返回数据组装
$result = [];
if($perPrice > 0){
$result = ['0-'.$perPrice]; //定义第一个区间
$stepPrice = $perPrice;
for ($addPrice = $stepPrice+1; $addPrice < $goodsPrice['max'];) {
if(count($result) == $showPriceNum){
break;
}
//下个区间结束值
$stepPrice = $addPrice + $perPrice;
//除去首个数字外 剩下所有为 9 效果 2999
$stepPrice = substr(intval($stepPrice), 0, 1).str_repeat('9',(strlen(intval($stepPrice)) - 1));
$result[] = $addPrice.'-'.$stepPrice; //下个区间段
$addPrice = $stepPrice + 1; // 下个区间开始 当前最大值 +1
}
//置换max价格 把数据最后的 值 替换为 最大值
$result[count($result)-1] = str_replace("-".$stepPrice,"-".ceil($goodsPrice['max']),$result[count($result)-1]);
return $result;
}
}
}
$price = new Goods();
$min = 85;
$max = 10056;
$num = 6;
$result = $price->getGoodsPrice($min, $max, $num);
var_dump($result);
array (size=6)
0 => string '0-1662' (length=6)
1 => string '1663-3999' (length=9)
2 => string '4000-5999' (length=9)
3 => string '6000-7999' (length=9)
4 => string '8000-9999' (length=9)
5 => string '10000-10056' (length=11)