您现在的位置是:网站首页> php专栏 thinkphp
tp5实现按月查询价格的平均值
亦然2019-06-03 23:58:53【thinkphp】人已围观
简介最近有项目要实现统计最近几个月的售价平均值,并需要按类别分组,在此记录一下。
public function getAvg($type,$where){
if($type == 3){
//商铺
$shop_id = db('house_type')->where('name','like','%商铺%')->column("id"); ;
$shop = implode(',',$shop_id);
$where['house_type'] = ['in',$shop];
}else{
$where['type'] = $type;
}
$beginThismonth = strtotime(date('Y-m-01 00:00:00',strtotime('-4 month')));
$endThismonth = mktime(23,59,59,date('m'),date('t'),date('Y'));
$array = self::getMonthArr($beginThismonth,$endThismonth);
$db = Db::table('h_house')
->field('FROM_UNIXTIME(create_time,"%m") as time,FROM_UNIXTIME(create_time,"%Y-%m") as avg_time,cast(avg(sold_price) AS DECIMAL(10,0)) as avgPrice')
->where($where)
->whereTime('create_time', 'between', [$beginThismonth, $endThismonth])
->group('avg_time')
->select();
//分组没有数据的 追加0
if(count($db) < 5){
$arr = $array;
foreach ($db as $key => $value) {
$time[] = $value['avg_time'];
}
$ex = array_diff($arr,$time);
foreach ($ex as $key => $value) {
$month = explode('-',$value);
array_push($db,array('time'=>$month[1],'avg_time'=>$value,'avgPrice'=>0));
}
}
//数组排序
// 取得列的列表
foreach ($db as $key => $row)
{
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $db);
return $db;
}
/**
* 生成从开始月份到结束月份的月份数组
* @param unknown_type $start
* @param unknown_type $end
*/
function getMonthArr($start, $end)
{
$start = empty($start) ? date('Y-m',strtotime('-1 month')) : $start;
$end = empty($end) ? date('Y-m') : $end;
//转为时间戳
$st = $start;
$et = $end;
$t = $st;
$i = 0;
while($t <= $et)
{
//这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
//看不懂自己想去
$d[$i] = trim(date('Y-m',$t),' ');
$t += strtotime('+1 month', $t)-$t;
$i++;
}
return $d;
}
很赞哦!()
上一篇: 这已经是第一篇了!




