重组数组

时间:2011-11-28 04:30:28

标签: iphone json nsarray

我得到了json的返回数组,

[{"date": "2011-01-01", "title": "aaa"},
 {"date": "2011-01-01", "title": "bbb"},
 {"date": "2011-01-01", "title": "ccc"},
 {"date": "2011-01-02", "title": "ddd"},
 {"date": "2011-01-02", "title": "eee"},
 {"date": "2011-01-03", "title": "fff"},
 {"date": "2011-01-03", "title": "ggg"}]

我使用这些代码来获取值:

NSDictionary *jsonDictionary = [jsonArray objectAtIndex:i];
NSString *date = [jsonDictionary objectForKey:@"dispalyDate"];
NSString *title = [jsonDictionary objectForKey:@"title"];

问题是如何根据相同的日期重组数组或创建新数组,例如

date = 2011-01-01
aaa、bbb、ccc

date = 2011-01-02
ddd、eee

date = 2011-01-03
fff、ggg

1 个答案:

答案 0 :(得分:3)

像这样......

NSMutableDictionary *titlesByDate = [NSMutableDictionary dictionary];
for (NSDictionary *entry in jsonDictionary) {
    NSString *date = [entry objectForKey:@"date"];
    NSMutableArray *titles = [titlesByDate objectForKey:date];
    if (!titles) {
        titles = [NSMutableArray array];
        [titlesByDate setObject:titles forKey:date];
    }
    [titles addObject:[entry objectForKey:@"title"]];
}

现在你有一个字典,其中键是日期字符串,值是标题数组。如果你真的想要一个数组结果,那么你可以这样做:

NSMutableArray *array = [NSMutableArray array];
for (NSString *date in titlesByDate) {
    [array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
        date, @"date",
        [titlesByDate objectForKey:date], @"titles",
        nil];
}