From 4b5435e03916bd19e2f04616d250aa841de0c200 Mon Sep 17 00:00:00 2001 From: loshiqi <553578653@qq.com> Date: Thu, 27 Oct 2022 15:09:59 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0map=E5=88=87=E7=89=87?= =?UTF-8?q?=E5=80=BC=E9=A1=BA=E5=BA=8F=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- map.go | 40 ++++++++++++++++++++++++++++++++++++++++ map_test.go | 13 +++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/map.go b/map.go index 7b88735..8165b79 100644 --- a/map.go +++ b/map.go @@ -202,3 +202,43 @@ func HttpBuildStringQuery(data map[string]string) string { return strings.Trim(query, "&") } + +/** + * 对map切片 按值进行顺序 + * @param order desc/asc MapDate []map[string]interface{} + * @2022/10/27 + * @lo + */ +func MapSort(order, val string, MapDate []map[string]interface{}) ([]map[string]interface{}, error) { + type KVPair struct { + Key int + Val string + } + res := []map[string]interface{}{} + if order != "desc" && order != "asc" { + return res, errors.New("order parameter err") + } + if val == "" { + return res, errors.New("val parameter err") + } + if len(MapDate) < 1 { + return res, errors.New("MapDate parameter err") + } + tmpList := []KVPair{} + for k, item := range MapDate { + tmpList = append(tmpList, KVPair{Key: k, Val: ToStr(item[val])}) + } + if order == "desc" { + sort.Slice(tmpList, func(i, j int) bool { + return tmpList[i].Val > tmpList[j].Val // 降序 + }) + } else { + sort.Slice(tmpList, func(i, j int) bool { + return tmpList[i].Val < tmpList[j].Val // 升序 + }) + } + for _, tmp := range tmpList { + res = append(res, MapDate[tmp.Key]) + } + return res, nil +} diff --git a/map_test.go b/map_test.go index 79e17fa..4c1954a 100644 --- a/map_test.go +++ b/map_test.go @@ -6,10 +6,19 @@ import ( func Test_HttpBuildQuery(t *testing.T) { - list := map[string]string{"a": "b", "": "cdd", "b": ""} + a := map[string]interface{}{"id": "1", "name": "8","price":"2.3"} + b := map[string]interface{}{"id": "2", "name": "7","price":"2.8"} + c := map[string]interface{}{"id": "3", "name": "9","price":"2.1"} + list := []map[string]interface{}{} + list = append(list, a) + list = append(list, b) + list = append(list, c) + //ret := HttpBuildQuery(list) + ret, err := MapSort("asc", "name", list) - ret := HttpBuildQuery(list) + if err != nil { + } t.Log(ret) }