普通网友 2016-09-22 11:55
浏览 472
已采纳

在Golang中按子数组值分组切片

I have an array of subarrays in the following format

Array
(
    [0] => Array
        (
            [unit_id] => 6504
            [assignment_name] => Grade assignment 
            [assignment_description] => 
            [assignment_total_score] => 10
            [unit_type_name] => Homework
            [is_graded] => 1
            [standard_id] => 1219
            [scoring_type] => score
            [attempt_score] => 8
            [unit_duedate] => 2016-02-10 09:00:00
            [standard] => Array
                (

                    [0] => stdClass Object
                        (
                            [unit_id] => 6504
                            [is_formal] => 1
                            [assignment_name] => Grade assignment 
                            [assignment_description] => 
                            [standard_id] => 1220
                            [standard_name] => 9-10.RL.3
                            [standard_description] => Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a 
                        )

                )

        )

    [1] => Array
        (
            [unit_id] => 8584
            [assignment_name] => Sine and Cosecant Graphs
            [assignment_description] => Define the sine and cosecant graphs using a unit circle
            [assignment_total_score] => 15
            [unit_type_name] => Paper
            [scoring_type] => score
            [attempt_score] => 0
            [unit_duedate] => 2016-04-29 09:00:00
            [standard] => Array
                (

                    [0] => stdClass Object
                        (
                            [unit_id] => 8584
                            [is_formal] => 1
                            [assignment_name] => Sine and Cosecant Graphs
                            [assignment_description] => Define the sine and cosecant graphs using a unit circle
                            [assignment_total_score] => 15
                            [standard_id] => 82790
                            [standard_name] => 9-10.RL.7


                )

        )

    [2] => Array
        (
            [unit_id] => 11611
            [assignment_name] => Adding 5 + 3 + 6
            [assignment_description] => 
            [assignment_total_score] => 10
            [unit_type_name] => Homework
            [standard_id] => 82772
            [scoring_type] => score
            [attempt_score] => 0
            [unit_duedate] => 2016-08-23 19:00:00
            [standard] => Array
                (
                    [0] => stdClass Object
                        (
                            [unit_id] => 11611
                            [is_formal] => 1
                            [assignment_name] => Adding 5 + 3 + 6
                            [assignment_description] => 
                            [assignment_total_score] => 10
                            [standard_id] => 82772
                            [standard_name] => 9-10.RL.1

                        )

                )

        )

)

And I would like to group it into a new slice based on the unit_type_name field in each subarray.

How can I group the slice by unit_type_name? Is there any native GO functions are available to do this? if I for loop the above then I will get a duplicate one, how can I avoid that?

  • 写回答

1条回答 默认 最新

  • doujiao2443 2016-09-23 13:27
    关注

    I do not think golang has build-in functionality to help you do that (I may be wrong). My Assuption is that the php array will be converted to a json object. I managed to get the code below to help you sort your array (In JSON format) a based on the unit_type_name I created two structs which have json values similar to what the array keys would be

    //StandardType ...
    type StandardType struct {
        UnitID                int    `json:"unit_id"`
        IsFormal              int    `json:"is_formal"`
        AssignmentName        string `json:"assignment_name"`
        AssignmentDescription string `json:"assignment_description"`
        StandardID            int    `json:"standard_id"`
        StandardName          string `json:"standard_name"`
        StandardDescription   string `json:"standard_description"`
    }
    
    //AutoGenerated ...
    type AutoGenerated struct {
        UnitID                int            `json:"unit_id"`
        AssignmentName        string         `json:"assignment_name"`
        AssignmentDescription string         `json:"assignment_description"`
        AssignmentTotalScore  int            `json:"assignment_total_score"`
        UnitTypeName          string         `json:"unit_type_name"`
        IsGraded              int            `json:"is_graded"`
        StandardID            int            `json:"standard_id"`
        ScoringType           string         `json:"scoring_type"`
        AttemptScore          int            `json:"attempt_score"`
        UnitDuedate           string         `json:"unit_duedate"`
        Standard              []StandardType `json:"standard"`
    }
    var jsonData = ``
    func main() { 
        m := []AutoGenerated{}
        err := json.Unmarshal([]byte(jsonData), &m)
        if err != nil {
            panic(err)
        }
    

    I created a map to hold the unit_type_name keys

        sliceKeys := make(map[string]string)
    

    I created also map to hold the arrays that have similar unit_type_name keys in an AutoGenerated array

        groupedSlices := make(map[string][]AutoGenerated)
    

    Then I loop through the decoded json string searching for the unit_type_name

        for i := range m {
    

    If a unit_type_name already exists in the key slice I add the array item to the group slice

          if _, ok := sliceKeys[m[i].UnitTypeName]; ok {
            autogenerated := groupedSlices[m[i].UnitTypeName]
            autogenerated = append(autogenerated, m[i])
            groupedSlices[m[i].UnitTypeName] = autogenerated
          } else {
    

    Else I create a new array key and add the item to it

            sliceKeys[m[i].UnitTypeName] = m[i].UnitTypeName
            autogenerated := []AutoGenerated{}
            autogenerated = append(autogenerated, m[i])
            groupedSlices[m[i].UnitTypeName] = autogenerated
         }
      }
      fmt.Println(sliceKeys)
      fmt.Println(groupedSlices)
    }
    

    input:

    [{"unit_id": 6504,"assignment_name": "Grade assignment","assignment_description": "","assignment_total_score": 10,"unit_type_name": "Homework","is_graded": 1,"standard_id": 1219,
    "scoring_type": "score","attempt_score": 8,"unit_duedate": "2016-02-10 09:00:00",
    "standard": [{"unit_id": 6504,"is_formal": 1,"assignment_name": "Grade assignment","assignment_description": "",
    "standard_id": 1220,"standard_name": "9-10.RL.3","standard_description": "Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a "
    }]},{"unit_id": 6504,"assignment_name": "Grade assignment","assignment_description": "","assignment_total_score": 10,
    "unit_type_name": "Paper","is_graded": 1,"standard_id": 1219,"scoring_type": "score","attempt_score": 8,"unit_duedate": "2016-02-10 09:00:00","standard": [{"unit_id": 6504,"is_formal": 1,"assignment_name": "Grade assignment","assignment_description": "","standard_id": 1220,"standard_name": "9-10.RL.3","standard_description": "Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a "}]},{
    "unit_id": 6504,"assignment_name": "Grade assignment","assignment_description": "",
    "assignment_total_score": 10,"unit_type_name": "Aything else","is_graded": 1,"standard_id": 1219,
    "scoring_type": "score","attempt_score": 8,"unit_duedate": "2016-02-10 09:00:00","standard": [{
    "unit_id": 6504,"is_formal": 1,"assignment_name": "Grade assignment","assignment_description": "","standard_id": 1220,
    "standard_name": "9-10.RL.3","standard_description": "Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a "}]}]
    

    output:

    map[Homework:Homework Paper:Paper Aything else:Aything else]
    
    map[
    Homework:[
    {6504 Grade assignment  10 Homework 1 1219 score 8 2016-02-10 09:00:00 [{6504 1 Grade assignment  1220 9-10.RL.3 Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a }]}
    ] 
    
    Paper:[
    {6504 Grade assignment  10 Paper 1 1219 score 8 2016-02-10 09:00:00 [{6504 1 Grade assignment  1220 9-10.RL.3 Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a }]}
    ] 
    
    Aything else:[
    {6504 Grade assignment  10 Aything else 1 1219 score 8 2016-02-10 09:00:00 [{6504 1 Grade assignment  1220 9-10.RL.3 Analyze how complex characters (e.g., those with multiple or conflicting motivations) develop over the course of a }]}]
    

    ]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)