如何对包含数组和字典的数组进行排序键号

问题描述:

我想对数组进行排序。这里是我的Array结构。如何对包含数组和字典的数组进行排序键号

(

    (

     //SubArray 
) 

{ 
    date =“2016-03-16”; 
} 

) 

------ 
------ 

如何使用排序描述符进行排序?

可能吗? (或)

我是否需要改变我的数组结构(将子数组移动到字典..)。

+0

请问我可以知道倒票的原因 –

把你的字典到一个数组,这样做

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; 
yourArray=[yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; 
dictionaryArray = [yourArray copy]; 
+0

@idevloper,但是我需要顶级数组属于那个日期 –

+0

你的答案不适用于与该问题有关的问题,你是否看到过这个'( // Array )',你如何排序这 –

下面就是我的回答试试这个,如果它帮助,它长期的解决方案,但它帮助我获得数组这是短期明智日期

// my Json responce in string 
    NSString *Str = @"{\"Array\":[{\"date\":\"01/15/2016\",\"Subarr\":[\"A\",\"B\"]},{\"date\":\"01/06/2016\",\"Subarr\":[\"C\",\"D\"]},{\"date\":\"16/02/2015\",\"Subarr\":[\"E\",\"F\"]},{\"date\":\"22/02/2016\",\"Subarr\":[\"G\",\"H\"]}]}"; 
    // convert in to nsdata 
    NSData *data = [Str dataUsingEncoding:NSUTF8StringEncoding]; 
    // final json responce 
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    // create a new Dictionary for shorting 
    NSMutableDictionary *Dic = [[NSMutableDictionary alloc] init]; 
    // get all main array 
    NSArray *Temp1 = [json valueForKey:@"Array"]; 
    for (int i = 0; i<Temp1.count; i++) { 
     id subjson = Temp1[i]; 
     // get date and store in key string 
     NSString *Key = [subjson valueForKey:@"date"]; 
     // get sub array and store in array object 
     NSArray *Object = [subjson valueForKey:@"Subarr"]; 
     // now store object with key is date 
     [Dic setObject:Object forKey:Key]; 
    } 
    // after get all key from created Dictionary 
    NSArray *keys = [Dic allKeys]; 
    // short key date wise 
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { 
     NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
     [format setDateFormat:@"DD/MM/YYYY"]; 
     NSDate *FirstDate = [format dateFromString:a]; 
     NSDate *SecondDate = [format dateFromString:b]; 
     return [FirstDate compare:SecondDate];; 
    }]; 
    // you can get short array by date wise 
    NSLog(@"%@",sortedArray); 
    // now you want array which is short wise date 
    NSMutableArray *Final_shortarr = [[NSMutableArray alloc] init]; 
    for (int i=0; i<sortedArray.count; i++) { 
     NSString *Key = [sortedArray objectAtIndex:i]; 
     [Final_shortarr addObject:[Dic objectForKey:Key]]; 
    } 
    // this array give final short datewise array 
    NSLog(@"%@",Final_shortarr); 
+0

看来你已经添加子字典到字典? –

+0

是与关键是日期 –

+0

如果我改变我的阵列结构像移动子阵列到字典,解决方案是非常简单的像上面的答案。 –