123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package utils
- import (
- "reflect"
- "sort"
- "strconv"
- "golang.org/x/exp/constraints"
- )
- // MapValues 获取Map中所有的Key,作为切片返回,可排序
- func MapValues[K constraints.Ordered, V any](m map[K]V, order bool) []V {
- values := make([]V, 0, len(m))
- if !order {
- for _, v := range m {
- values = append(values, v)
- }
- } else {
- keys := MapKeys(m, true)
- for i := 0; i < len(keys); i++ {
- values = append(values, m[keys[i]])
- }
- }
- return values
- }
- // MapKeys 获取Map中所有的Value,作为切片返回,可排序
- func MapKeys[K constraints.Ordered, V any](m map[K]V, order bool) []K {
- keys := make([]K, 0, len(m))
- for k := range m {
- keys = append(keys, k)
- }
- if order {
- sort.SliceStable(keys, func(i, j int) bool {
- return keys[i] < keys[j]
- })
- }
- return keys
- }
- // Slice2Map 切片转化为map,map的key从1开始累加
- func Slice2Map[T any](s []T) map[int64]T {
- m := make(map[int64]T, len(s))
- for i, v := range s {
- m[int64(i+1)] = v
- }
- return m
- }
- // ArrayColumns 参照php ArrayColumns
- func ArrayColumns[T any](input []T, column string) map[string]T {
- var output = make(map[string]T, len(input))
- var key string
- if len(input) < 1 {
- return output
- }
- immutableT := reflect.TypeOf(input[0])
- field, ok := immutableT.FieldByName(column)
- if !ok {
- return output
- }
- for _, row := range input {
- switch field.Type.Kind() {
- case reflect.String:
- key = reflect.ValueOf(row).FieldByName(column).Interface().(string)
- case reflect.Int64:
- tk := reflect.ValueOf(row).FieldByName(column).Interface().(int64)
- key = strconv.Itoa(int(tk))
- case reflect.Int:
- tk := reflect.ValueOf(row).FieldByName(column).Interface().(int)
- key = strconv.Itoa(tk)
- }
- output[key] = row
- }
- return output
- }
|