我是 Swift 新手,在对多维数组进行排序时遇到困难。 (Alamofire 和 SwiftyJSON 已安装并导入)
我想按照每个人的最高分对主 JSON 数组进行排序。 我能够对每个的[“分数”]进行排序
for x in 0..<JSONArray.count{
let b = JSONArray[x]["scores"].array?.sorted{$0["test"] < $1["test"]}
}
但是,我不知道如何影响主 JSON 数组顺序。
这是我的 JSON 文件,
{"students": [{
"id": 1,
"profile": [{
"name": "Kenneth",
"age": 19
}],
"scores": [{
"test": 62
}, {
"test": 80
}, {
"test": 95
}]
}, {
"id": 2,
"profile": [{
"name": "Thomas",
"age": 12
}],
"scores": [{
"test": 60
}, {
"test": 92
}, {
"test": 30
}]
}, {
"id": 3,
"profile": [{
"name": "May",
"age": 15
}],
"scores": [{
"test": 62
}, {
"test": 72
}, {
"test": 100
}]
}]}
我想要的最终 JSON 输出是
{"students": [{
"id": 3,
"profile": [{
"name": "May",
"age": 15
}],
"scores": [{
"test": 100
}, {
"test": 72
}, {
"test": 62
}]
}, {
"id": 1,
"profile": [{
"name": "Kenneth",
"age": 19
}],
"scores": [{
"test": 95
}, {
"test": 80
}, {
"test": 62
}]
}, {
"id": 2,
"profile": [{
"name": "Thomas",
"age": 12
}],
"scores": [{
"test": 92
}, {
"test": 60
}, {
"test": 30
}]
}]}
感谢您的帮助!
最佳答案
当前您正在按升序对 scores
数组进行排序,您需要将其按降序排序,然后在主 json 数组中设置此排序数组。之后使用 scores
数组的第一个值对主数组进行排序。
//Forst soret main json by max score
var jsonArray = json["students"].arrayValue
//Sort score array
for x in 0..<jsonArray.count{
let sortedScores = jsonArray[x]["scores"].arrayValue.sorted{$0["test"] > $1["test"]}
jsonArray[x]["scores"] = JSON(sortedScores)
}
//Sort main array using first object of scores array
let sortedJSON = jsonArray.sorted { $0["scores"].arrayValue[0]["test"].intValue > $1["scores"].arrayValue[0]["test"].intValue }
print(sortedJSON)
关于arrays - 按子级值对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289349/