Php iOS JSON响应两次,JSON Null

Php iOS JSON响应两次,JSON Null,php,ios,json,nsdata,Php,Ios,Json,Nsdata,为什么我的json响应在某些情况下会重复两次(无法隔离),从而导致我的jsonData为(null)。我对Android使用相同的php,但只有我的iOS看到了这个问题。下面是我的objective-C代码,它会生成两次响应—有时: NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString

为什么我的json响应在某些情况下会重复两次(无法隔离),从而导致我的jsonData为(null)。我对Android使用相同的php,但只有我的iOS看到了这个问题。下面是我的objective-C代码,它会生成两次响应—有时:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"jsonData: %@",jsonData);

构建输出数组,然后输出json。可能发生的情况是,您第一次发送的是有效的json,当您继续使用ech时,它将变得无效,因为您需要以下字符串:

{test: 1}{hello: 2}
不是有效的json

$output = array();

//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){

//store the returned data into a variable
$output[] = $list;
}

//encode the returned data in JSON format
echo json_encode($output);

如果在正常情况下,数据库只返回一行,那么这段代码的PHP部分可以工作。但是,如果输入表中有两行或更多行,其中ts对于该用户是相等的,则json数据将被多次打印,因为echo位于while loop.kimg中-您是正确的,因为存在两个相同的时间戳,因此导致json无效。非常感谢。柯克-谢谢你的提示。时间戳相同,导致两个json输出,因此无效。
$output = array();

//create a while loop that places the returned data into an array
while ($list = mysql_fetch_assoc($query)){

//store the returned data into a variable
$output[] = $list;
}

//encode the returned data in JSON format
echo json_encode($output);