数据结构优化

This commit is contained in:
李琦
2026-01-20 11:12:01 +08:00
parent b088ba48be
commit 4aa757082b
9 changed files with 519 additions and 51 deletions

View File

@@ -174,7 +174,16 @@ func ExtractProvinceFromRegion(region string) string {
return "未知"
}
// 所有省份列表34个
var allProvinces = []string{
"北京", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江",
"上海", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南",
"湖北", "湖南", "广东", "广西", "海南", "重庆", "四川", "贵州",
"云南", "西藏", "陕西", "甘肃", "青海", "宁夏", "新疆", "台湾", "香港", "澳门",
}
// GetUserRegions 获取用户地域分布(使用 access_logs 表的 region 字段)
// 返回所有34个省份的数据没有数据的省份 Count 设为 0
func GetUserRegions(startDate, endDate string) ([]struct {
Region string
Count int
@@ -210,15 +219,18 @@ func GetUserRegions(startDate, endDate string) ([]struct {
provinceMap := make(map[string]int)
for _, r := range results {
province := ExtractProvinceFromRegion(r.Region)
provinceMap[province] += r.Count
if province != "未知" {
provinceMap[province] += r.Count
}
}
// 转换为结果格式
// 为所有省份生成数据没有数据的设为0
var finalResults []struct {
Region string
Count int
}
for province, count := range provinceMap {
for _, province := range allProvinces {
count := provinceMap[province]
finalResults = append(finalResults, struct {
Region string
Count int
@@ -228,14 +240,5 @@ func GetUserRegions(startDate, endDate string) ([]struct {
})
}
// 按数量排序
for i := 0; i < len(finalResults)-1; i++ {
for j := i + 1; j < len(finalResults); j++ {
if finalResults[i].Count < finalResults[j].Count {
finalResults[i], finalResults[j] = finalResults[j], finalResults[i]
}
}
}
return finalResults, nil
}