數組通過time拆分新的數組(包含多個時間段的數組)
初始json數據如下:
{
info_list : [
{
id : 110,
time : "2016-6-20",
name : "張三"
},
{
id : 111,
time : "2016-6-20",
name : "李四"
},
{
id : 112,
time : "2016-6-21",
name : "王五"
},
{
id : 113,
time : "2016-6-22",
name : "趙六"
}
]
}
改造后如下:
{
info_list : [
[
{
id : 110,
time : "2016-6-20",
name : "張三"
},
{
id : 111,
time : "2016-6-20",
name : "李四"
}
],
[
{
id : 112,
time : "2016-6-21",
name : "王五"
}
],
[
{
id : 113,
time : "2016-6-22",
name : "趙六"
}
]
]
}
也就是數組中包含數組,多加了一層.
- (NSMutableArray *)arraySplitSubArrays:(NSArray *)array {
// 數組去重,根據數組元素對象中time字段去重
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
for(ShoppingDetailsRecordModel *obj in array)
{
[dic setValue:obj forKey:[Tool timeStampWithtimeStr:obj.time dateFormat:@"yyyy-MM-dd"]];
}
NSMutableArray *tempArr = [NSMutableArray array];
for (NSString *dictKey in dic) {
[tempArr addObject:dictKey];
}
NSArray *sortedArray = [tempArr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"排序后:%@",sortedArray);
// 字典重不會有重復值,allKeys返回的是無序的數組
NSLog(@"去重后字典:%@",[dic allKeys]);
NSMutableArray *temps = [NSMutableArray array];
for (NSString *dictKey in sortedArray) {
NSMutableArray *subTemps = [NSMutableArray array];
for (ShoppingDetailsRecordModel *obj in array) {
if ([dictKey isEqualToString:[Tool timeStampWithtimeStr:obj.time dateFormat:@"yyyy-MM-dd"]]) {
[subTemps addObject:obj];
}
}
[temps addObject:subTemps];
}
// 排序后,元素倒序的,逆向遍歷
NSEnumerator *enumerator = [temps reverseObjectEnumerator];
temps = (NSMutableArray*)[enumerator allObjects];
ZLLog(@"temps:%@",temps);
return temps;
}