php - PHP for iOS 中的 JSON 编码多重查询返回

标签 php ios json

我按照 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/

相关文章:

php - 选择表 A 的所有左连接列,其中包含多个不影响显示所有表 A 的 where

php - MVC(Laravel)在哪里添加逻辑

iphone - 多个 UIViewController 子类中的相同 UIView 子类?

ios - 使用 [id class] 作为指针

ios - 如何在ios中使用nsmutableurlrequest发送递归json请求?

php - 如何使用 AJAX 将数组发布到 PHP?

php - 使用 IP 地址敏感的 View 计数器是否会为 MYSQL/PHP 带来过多的工作量?

ios - Swift - 核心图形和设置背景颜色?

c# - 如何从json创建一个c#对象

javascript - 在angularjs中不显示包含 `.`的对象项