我按照 Ray Wenderlich 的教程创建了一个 Web 服务/将其连接到 iOS,但他的示例返回的结果在查询中只返回了一个可能的行。我想以 JSON 格式返回所有可能的结果,但我很困惑如何将它们存储为正确的 key 。
这是我对 PHP 的了解:
$stmt = $this->db->prepare('SELECT userID, lat, lng FROM Connections WHERE airline=? AND flight_number=? ');
$stmt->bind_param("si", $airline, $flight_number);
$stmt->execute();
$stmt->bind_result($otherUser, $otherLat, $otherLng);
while ($stmt->fetch()) {
break;
}
$stmt->close();
if ($otherUser) {
//sendResponse(403, 'Code already used');
//return false;
$myLatLng = "$lat,$long";
$otherLatLng="$otherLat,$otherLng";
$results = getDistanceBetween($myLatLng,$otherLatLng);
$miles = $results[0];
$minutes = $results[1];
$result = array(
"other_user" => $otherUser,
"distance" => $miles,
"duration" => $minutes,
);
sendResponse(200, json_encode($result));
return true;
}
在 Obj-C 方面,我使用以下代码获取这些值:
if (request.responseStatusCode == 200) {
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSString *otherUser = [responseDict objectForKey:@"other_user"];
NSString *otherDistance = [responseDict objectForKey:@"distance"];
NSString *otherDuration = [responseDict objectForKey:@"duration"];
有人可以帮我吗?
最佳答案
在 PHP 代码中,您想要创建一个嵌套数组,然后使用 json_encode()。这是之前的一个问题,其中包含有关您的问题的 PHP 方面的更多详细信息:How to create an array for JSON using PHP?
在 iOS 端,由于您的 Web 服务将返回表示多个项目的 JSON 响应,因此在响应字符串上调用 JSONValue
将返回一个 NSArray
对象,而不是 NSDictionary
。然后,您可以迭代数组中的项目(它们本身就是 NSDictionary 项目)并提取您需要的值。
NSString *responseString = [request responseString];
NSArray *responseArray = [responseString JSONValue];
for (NSDictionary* item in responseArray) {
NSString *otherUser = [item objectForKey:@"other_user"];
NSString *otherDistance = [item objectForKey:@"distance"];
NSString *otherDuration = [item objectForKey:@"duration"];
}
关于php - PHP for iOS 中的 JSON 编码多重查询返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9404794/