常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
2.1 KiB

3 years ago
3 years ago
  1. package helper
  2. import (
  3. "errors"
  4. "sort"
  5. "strings"
  6. )
  7. func MergeStringMap(x, y map[string]string) map[string]string {
  8. n := make(map[string]string)
  9. for i, v := range x {
  10. for j, w := range y {
  11. if i == j {
  12. n[i] = w
  13. } else {
  14. if _, ok := n[i]; !ok {
  15. n[i] = v
  16. }
  17. if _, ok := n[j]; !ok {
  18. n[j] = w
  19. }
  20. }
  21. }
  22. }
  23. return n
  24. }
  25. /**
  26. * 转换为map string数组
  27. * 2021/1/5
  28. * gz
  29. */
  30. func ToMapStringArray(x interface{}) ([]map[string]string, error) {
  31. list, ok := x.([]interface{})
  32. if !ok {
  33. return []map[string]string{}, errors.New("type error")
  34. }
  35. if len(list) < 1 {
  36. return []map[string]string{}, nil
  37. }
  38. var ret []map[string]string = make([]map[string]string, len(list))
  39. var tmp map[string]interface{}
  40. var map_tmp map[string]string
  41. var err error
  42. for key, item := range list {
  43. if tmp, ok = item.(map[string]interface{}); ok {
  44. map_tmp = make(map[string]string)
  45. for k, v := range tmp {
  46. map_tmp[k] = ToStr(v)
  47. }
  48. ret[key] = map_tmp
  49. } else {
  50. err = errors.New("data type error")
  51. break
  52. }
  53. }
  54. return ret, err
  55. }
  56. /**
  57. * 将map[string]string数组转成map[string]interface数组
  58. */
  59. func MapStringToInterfaceArr(src []map[string]string) []map[string]interface{} {
  60. var dest []map[string]interface{}
  61. for i := range src {
  62. m := src[i]
  63. n := make(map[string]interface{})
  64. for k, v := range m {
  65. n[k] = interface{}(v)
  66. }
  67. dest = append(dest, n)
  68. }
  69. return dest
  70. }
  71. /**
  72. * 将map[string]string转成map[string]interface
  73. */
  74. func MapStringToInterface(src map[string]string) map[string]interface{} {
  75. target := make(map[string]interface{})
  76. for k, v := range src {
  77. target[k] = interface{}(v)
  78. }
  79. return target
  80. }
  81. /**
  82. * 对map进行字典序排序
  83. * @param data map[string]string
  84. * @2020/12/28
  85. * @linsen
  86. */
  87. func HttpBuildQuery(data map[string]string) string {
  88. keySlice := []string{}
  89. for k, _ := range data {
  90. keySlice = append(keySlice, k)
  91. }
  92. sort.Strings(keySlice) //排序字符串
  93. var query string
  94. for _, value := range keySlice {
  95. if value != "" && data[value] != "" {
  96. query += StringJoin(value, "=", data[value], "&")
  97. }
  98. }
  99. return strings.Trim(query, "&")
  100. }