zoukankan      html  css  js  c++  java
  • golang map数组根据某个字段值排序

    package main

    import (
    "fmt"
    "math/rand"
    "sort"
    "strconv"
    "zentaotimer/libs/github.com/wonderivan/logger"
    )

    type MapsSort struct {
    Key string
    MapList []map[string] interface{}
    }

    func (m *MapsSort) Len() int {
    return len(m.MapList)
    }

    func (m *MapsSort) Less(i, j int) bool {
    var ivalue float64
    var jvalue float64
    var err error
    fmt.Println(m.Key)
    switch m.MapList[i][m.Key].(type) {
    case string:
    ivalue,err = strconv.ParseFloat(m.MapList[i][m.Key].(string),64)
    if err != nil {
    logger.Error("map数组排序string转float失败:%v",err)
    return true
    }
    case int:
    ivalue = float64(m.MapList[i][m.Key].(int))
    case float64:
    ivalue = m.MapList[i][m.Key].(float64)
    case int64:
    ivalue = float64(m.MapList[i][m.Key].(int64))
    }
    switch m.MapList[j][m.Key].(type) {
    case string:
    jvalue,err = strconv.ParseFloat(m.MapList[j][m.Key].(string),64)
    if err != nil {
    logger.Error("map数组排序string转float失败:%v",err)
    return true
    }
    case int:
    jvalue = float64(m.MapList[j][m.Key].(int))
    case float64:
    jvalue = m.MapList[j][m.Key].(float64)
    case int64:
    jvalue = float64(m.MapList[j][m.Key].(int64))
    }
    return ivalue > jvalue
    }

    func (m *MapsSort) Swap(i, j int) {
    m.MapList[i],m.MapList[j] = m.MapList[j],m.MapList[i]
    }

    func main() {
    mapsSort := MapsSort{}
    mapsSort.Key = "data"
    maps:= make([]map[string] interface{},0)
    for i:=0 ; i<10;i++ {
    data := rand.Float64()
    mapTemp := make(map[string] interface{})
    mapTemp["data"] = data
    mapTemp["aaa"] = fmt.Sprintf("aaa%d",i)
    maps = append(maps, mapTemp)
    }

    mapTemp := make(map[string] interface{})
    mapTemp["data"] = "1.001"
    mapTemp["aaa"] = fmt.Sprintf("aaa")
    maps = append(maps, mapTemp)
    fmt.Println(maps)
    mapsSort.MapList = maps
    fmt.Println(mapsSort)
    sort.Sort(&mapsSort)
    fmt.Println(mapsSort)
    }

      

  • 相关阅读:
    索引的结构和性能的关系
    TP5的多图上传
    TP5页面更改数字进行AJAX排序
    安装Git版本控制系统 以及Git Bash的基础命令
    tp5 前台 点击显示一个弹窗
    Tp5 (轮回) 多个富文本应用
    Tp5 (轮回) AJAX请求写搜索页面
    安装 SVN 服务器
    Tp5(轮回)------单图上传 运用AJAX 请求
    TP5中(通过一个表去取另一个表的相对应的名称)
  • 原文地址:https://www.cnblogs.com/zipon/p/12901071.html
Copyright © 2011-2022 走看看