2

我有一个以这种方式组织的字典数组:

[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}

你能帮助我吗?

4

1 回答 1

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);
于 2012-12-11T19:26:54.640 回答