duan48961411
2016-09-22 11:55
浏览 375
已采纳

在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 }]}]
    

    ]

    点赞 打赏 评论

相关推荐 更多相似问题