slice_tree.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/database/gdb"
  5. "github.com/gogf/gf/util/gconv"
  6. "strings"
  7. )
  8. //有层级关系的数组,父级-》子级 排序
  9. func ParentSonSort(list gdb.List, params ...interface{}) gdb.List {
  10. args := make([]interface{}, 8)
  11. for k, v := range params {
  12. if k == 8 {
  13. break
  14. }
  15. args[k] = v
  16. }
  17. var (
  18. pid int //父级id
  19. level int //层级数
  20. fieldName string //父级id键名
  21. id string //id键名
  22. levelName string //层级名称
  23. title string //标题名称
  24. breaks int //中断层级
  25. prefixStr string //字符串前缀
  26. )
  27. pid = gconv.Int(GetSliceByKey(args, 0, 0))
  28. level = gconv.Int(GetSliceByKey(args, 1, 0))
  29. fieldName = gconv.String(GetSliceByKey(args, 2, "pid"))
  30. id = gconv.String(GetSliceByKey(args, 3, "id"))
  31. levelName = gconv.String(GetSliceByKey(args, 4, "flg"))
  32. title = gconv.String(GetSliceByKey(args, 5, "title"))
  33. breaks = gconv.Int(GetSliceByKey(args, 6, -1))
  34. prefixStr = gconv.String(GetSliceByKey(args, 7, "  "))
  35. //定义一个新slice用于返回
  36. var returnSlice gdb.List
  37. for _, v := range list {
  38. if pid == gconv.Int(v[fieldName]) {
  39. v[levelName] = level
  40. levelClone := level
  41. titlePrefix := ""
  42. for {
  43. if levelClone < 0 {
  44. break
  45. }
  46. titlePrefix = strings.Repeat(prefixStr, 2)
  47. levelClone--
  48. }
  49. titlePrefix += "├"
  50. if level == 0 {
  51. v["title_prefix"] = ""
  52. } else {
  53. v["title_prefix"] = titlePrefix
  54. }
  55. v["title_show"] = fmt.Sprintf("%s%s", v["title_prefix"], v[title])
  56. returnSlice = append(returnSlice, v)
  57. if breaks != -1 && breaks == level {
  58. continue
  59. }
  60. args[0] = v[id]
  61. args[1] = level + 1
  62. newSlice2 := ParentSonSort(list, args...)
  63. if len(newSlice2) > 0 {
  64. returnSlice = append(returnSlice, newSlice2...)
  65. }
  66. }
  67. }
  68. return returnSlice
  69. }
  70. //获取切片里的值 若为nil 可设置默认值val
  71. func GetSliceByKey(args []interface{}, key int, val interface{}) interface{} {
  72. var value interface{}
  73. if args[key] != nil {
  74. value = args[key]
  75. } else {
  76. value = val
  77. }
  78. return value
  79. }