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

I have an array of subarrays in the following format

``````Array
(
[0] => Array
(
[unit_id] => 6504
[assignment_description] =>
[assignment_total_score] => 10
[unit_type_name] => Homework
[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_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"`
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 "}]},{
"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 }]}]
``````

]

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

#### 悬赏问题

• ¥15 如何用QDomDocument读取内容为空格的xml数据
• ¥15 请阅读下面代码，帮我修改下代码
• ¥15 关于#microsoft#的问题：电脑启动后不显示桌面图标和窗口，除任务栏外无法操作任何东西
• ¥15 如何输入百度，显示本地下载的html文件页面，地址栏还显示百度的地址
• ¥15 通过kinect制作换装程序但是服装不贴合(标签-ar)
• ¥20 matlab如何绘制三维瀑布图
• ¥15 关于用abap来解决动态规划的问题，但是要求输出索引值，这个是难点
• ¥15 在ISIS中什么是IP从地址
• ¥15 压测时，并发量过高时，响应时间出现尖刺
• ¥15 关于vmprotect3.8.4虚拟文件一项