golang 一维数组变二维数组,根据字段排序随机 发表于 2019-12-30 | 分类于 默认分类 | | 阅读次数: golang 一维数组变二维数组,json根据sort字段随机排序 golang 一维数组变二维数组,根据字段排序随机123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package mainimport ( "encoding/json" "fmt" "math/rand" "sort" "time")type DemoItemModel struct { ID int `json:"id"` Name string `json:"name"` SortValue int `json:"sort_value"`}type DemoModel []DemoItemModeltype SortKeys []inttype Groups struct { sortNum SortKeys data map[int]DemoModel}func (s SortKeys) Len() int { return len(s) }func (s SortKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }func (s SortKeys) Less(i, j int) bool { return s[i] < s[j] }func NewGroups() *Groups { return &Groups{ sortNum: make([]int, 0), data: make(map[int]DemoModel, 0), }}func (a *Groups) sortKey() []int { sort.Sort(a.sortNum) return a.sortNum}func (a *Groups) append(key int, item DemoItemModel) { a.data[key] = append(a.data[key], item)}func NewGroup() DemoModel { return make([]DemoItemModel, 0)}func (a *Groups) Add(num int) { a.sortNum = append(a.sortNum, num) a.data[num] = NewGroup()}func (a *Groups) Exits(num int) bool { if a.data[num] == nil { return false } return true}func GetRandomItems(a DemoModel) []DemoItemModel { groups := NewGroups() for _, item := range a { sort := item.SortValue if !groups.Exits(sort) { groups.Add(sort) } groups.append(sort, item) } return groups.Sort()}func (a *DemoModel) Random() DemoModel { length := len(*a) temp := make([]DemoItemModel, 0) r := rand.New(rand.NewSource(time.Now().UnixNano())) for { random := r.Intn(length) temp = append(temp, (*a)[random]) *a = append((*a)[:random], (*a)[random+1:]...) length = len(*a) if length < 1 { break } } *a = temp return temp}func (a *Groups) Sort() []DemoItemModel { temp := make([]DemoItemModel, 0) for _, item := range a.sortKey() { data := a.data[item] temp = append(temp, data.Random()...) } return temp}func main() { objString := `[{"id":1,"name":"1-1","sort_value":1},{"id":2,"name":"1-2","sort_value":1},{"id":3,"name":"2-1","sort_value":2},{"id":4,"name":"2-2","sort_value":2},{"id":5,"name":"2-3","sort_value":2},{"id":6,"name":"5-1","sort_value":5}]` var someOne []DemoItemModel if err := json.Unmarshal([]byte(objString), &someOne); err == nil { fmt.Println("================json str 转struct==") fmt.Println(someOne) } else { fmt.Println(err) } fmt.Println(22, GetRandomItems(someOne))} 感谢你的打赏哦! 打赏 微信支付 支付宝