我正在构建一个查询数据库的 IOS 应用程序。我总是把结果弄得乱七八糟,在应用程序的某些功能中,比如评论,让它们井井有条是至关重要的。很明显 JSON 正在返回一个字典,但我需要排序的结果。这是服务器端代码:
function sendResponse($status = 200, $body = '', $content_type = 'text/html') {
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
$result = array();
$i = 0;
$sqlGetComments = mysqli_query($link, "SELECT * FROM photo_comments WHERE photo_id='$photoID' ORDER BY post_date DESC");
while ($row = mysqli_fetch_array($sqlGetComments)) {
$result[$i] = array(
'photoID' => $row['photo_id'],
'userID' => $row['userID'],
'username' => $row['username'],
'comment' => $row['comment'],
'postedDate' => $row['post_date'],
);
$i++;
} // end while
sendResponse(200, json_encode($result));
我有解析它的 IOS 代码,但与我需要它的顺序不符。所以必须有一些我可以在服务器端做的事情。
更新,这是客户端代码:
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
[self updateComments:responseString];
}];
- (void)updateComments:(NSString *)update {
NSDictionary *root = [update JSONValue];
NSEnumerator *enumerator = [root keyEnumerator];
id key;
while (key = [enumerator nextObject]) {
NSDictionary *value = [root objectForKey:key];
_photoID = [value objectForKey:@"photoID"];
NSString *photoID = [value objectForKey:@"photoID"];
NSString *userID = [value objectForKey:@"userID"];
NSString *username = [value objectForKey:@"username"];
NSString *comment = [value objectForKey:@"comment"];
NSString *postedDate = [value objectForKey:@"postedDate"];
NSString *cellString = [NSString stringWithFormat:@"%@ \n %@ \n %@", username, comment, postedDate];
[_queryResultsMessage addObject:cellString];
}
[_tableView reloadData];
}
这是打印输出,请记住注释字段中的“测试”字符串是 JSON 字符串应该如何打印出来:
{"1":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 6","postedDate":"7 hrs ago"},"2":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 5","postedDate":"8 hrs ago"},"3":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 4","postedDate":"8 hrs ago"},"4":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 3","postedDate":"8 hrs ago"},"5":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 2","postedDate":"8 hrs ago"},"6":{"photoID":"1","userID":"17","username":"kismet","comment":"Test 1","postedDate":"8 hrs ago"}}
它可以打印出来,但我猜它在分配给 NSDictionary 时会变得混乱。如果没有人有任何答案,我会尝试通过将它分配给 NSArray 来摆弄它,看看我是否能以某种方式解析它。