github.com/gogf/gf/v2@v2.7.4/internal/utils/utils_list.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package utils
     8  
     9  import "fmt"
    10  
    11  // ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`.
    12  // Note that the item value may be type of slice.
    13  func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{} {
    14  	var (
    15  		s              = ""
    16  		m              = make(map[string]interface{})
    17  		tempMap        = make(map[string][]interface{})
    18  		hasMultiValues bool
    19  	)
    20  	for _, item := range list {
    21  		if k, ok := item[key]; ok {
    22  			s = fmt.Sprintf(`%v`, k)
    23  			tempMap[s] = append(tempMap[s], item)
    24  			if len(tempMap[s]) > 1 {
    25  				hasMultiValues = true
    26  			}
    27  		}
    28  	}
    29  	for k, v := range tempMap {
    30  		if hasMultiValues {
    31  			m[k] = v
    32  		} else {
    33  			m[k] = v[0]
    34  		}
    35  	}
    36  	return m
    37  }