我有一个以这种方式组织的字典数组:
[0] {@"code", 1} {@"category","drink"} ...and other value that aren't important
[1] {@"code", 2} {@"category","drink"}
[2] {@"code", 3} {@"category","drink"}
[3] {@"code", 4} {@"category","food"}
[4] {@"code", 5} {@"category","food"}
[5] {@"code", 6} {@"category","drink"}
以这种方式获得矩阵(数组数组)的最佳方法是什么......
[0] {1,2,3,6}
[1] {4,5}
你可以帮帮我吗?
答案 0 :(得分:1)
所以,如果你有一系列词典:
NSArray *originalArray = @[
@{@"code": @1, @"category":@"drink"},
@{@"code": @2, @"category":@"drink"},
@{@"code": @3, @"category":@"drink"},
@{@"code": @4, @"category":@"food"},
@{@"code": @5, @"category":@"food"},
@{@"code": @6, @"category":@"drink"}
];
你可以通过以下方式得到你想要的东西:
NSMutableArray *arrayOfCategories = [NSMutableArray array];
NSMutableArray *arrayOfArrayOfCodes = [NSMutableArray array];
for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];
NSInteger indexInArrayOfCategories = [arrayOfCategories indexOfObject:category];
NSMutableArray *arrayOfCodes;
if (indexInArrayOfCategories == NSNotFound)
{
indexInArrayOfCategories = [arrayOfCategories count];
arrayOfCodes = [NSMutableArray array];
[arrayOfArrayOfCodes addObject:arrayOfCodes];
[arrayOfCategories addObject:category];
}
else
{
arrayOfCodes = arrayOfArrayOfCodes[indexInArrayOfCategories];
}
[arrayOfCodes addObject:code];
}
NSLog(@"arrayOfArrayOfCodes = %@", arrayOfArrayOfCodes);
NSLog(@"arrayOfCategories = %@", arrayOfCategories);
请注意,您没有要求输入类别值数组,但我认为您要求的结果集在没有它的情况下毫无意义。
就个人而言,如果我想完成你所要求的(并且不需要那个单独的数组)并且顺序并不重要,我可能会倾向于使用数组值的字典(由类别值键控)代码,例如由以下原因引起的:
NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];
NSMutableArray *arrayForCategory = resultDictionary[category];
if (!arrayForCategory)
{
arrayForCategory = [NSMutableArray array];
resultDictionary[category] = arrayForCategory;
}
[arrayForCategory addObject:code];
}
NSLog(@"resultDictionary = %@", resultDictionary);