2012-02-22 39 views
0

我跟隨Ray Wenderlich的關於創建Web服務/關聯到iOS的教程,但他的示例返回的結果只有一個可能的行在查詢中返回。我想以JSON格式返回所有可能的結果,但我很困惑如何將它們存儲爲正確的密鑰。JSON編碼針對iOS的多個查詢返回PHP

下面是我對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"]; 

是否有人可以幫助我嗎?

回答

1

在你的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"]; 
} 
+0

謝謝你,但你知道我怎麼能返回JSON格式的數組?我對PHP/SQL/JSON部分感到困惑,但我甚至沒有考慮iOS陣列的一部分 – mkral 2012-02-22 23:57:04

+0

對不起,沒有看到有關PHP的頂部,謝謝! – mkral 2012-02-23 03:20:43