2014-01-17 17 views
0

我在這裏正確地處理事情嗎?這就是我的iOS開發者要我的數據庫值做一個應用程序,他正在上:難以置信的使用PHP返回對象的JSON

{「array」:[{「restID":1, etc.}, {「restID":2, etc.}, {「restID」:3, etc.}, {「restID」:4, etc.}], 「error":""} 

現在我的PHP代碼:

if ($stmt = $mysqli->prepare($query)) { 
    $stmt->bind_param("sssisi",$lat,$lat,$lng,$rest_price,$rest_genre,$eat_options); 
    $stmt->execute(); 
    $stmt->bind_result($rest_id,$user_id,$rest_name,$lat,$lng,$rest_price,$rest_rating,$rest_genre,$eat_options,$result); 
    //define error array 
    $errArray = array('error' => ''); 
    while ($stmt->fetch()) { 
     $row = array(
      'restID' => $rest_id, 
      'userID' => $user_id, 
      'rest_name' => $rest_name, 
      'lat' => $lat, 
      'lng' => $lng, 
      'restPrice' => $rest_price, 
      'restRating' => $rest_rating, 
      'restGenre' => $rest_genre, 
      'eat_options' => $eat_options); 

     $rows['array'][] = $row; 
    } 
    echo json_encode($rows); 
}.... 

,它輸出以下內容:

{「array」:[{「restID":1, etc.}, {「restID":2, etc.}, {「restID」:3, etc.}, {「restID」:4, etc.}]} 

注意我不能適應那裏的數組,否則我得到一些瘋狂的東西或PHP的語法錯誤。請指教!我怎樣才能得到第一個例子來處理我正在使用的當前代碼?我需要在我的PHP中操作什麼?同樣,我想

{「array」:[{「restID":1, etc.}, {「restID":2, etc.}, {「restID」:3, etc.}, {「restID」:4, etc.}], 「error":""} 

不:

{「array」:[{「restID":1, etc.}, {「restID":2, etc.}, {「restID」:3, etc.}, {「restID」:4, etc.}]} 
+0

我不知道我看到的問題。你有什麼問題?你得到什麼語法錯誤? –

+1

你想使用array_merge嗎? – spraff

+0

你的例子也很混亂。 – Zarathuztra

回答

3

錯誤數組就合併成排排列,像這樣:

echo json_encode(array_merge($rows, $errArray));

+0

謝謝Farkie!這完全是我需要的。對不起,我對每個人都感到困惑,因爲我沒有意識到我甚至可以使用array_merge函數。 – jflay

0

你讓errArray一個單獨的數組包含一個元素,一個叫做錯誤的鍵。您的代碼不會將其添加到以JSON編碼的其他代碼中。

2

試試這個

$rows['error'] = 'Error message' 
+1

這也是一個正確的答案,因爲我可以做$ rows ['array'] [] = $ row; $ rows ['error']。=''; (附加兩個PHP字符串)併產生相同的結果。哪個更好?要做到這一點或像以前一樣合併數組? – jflay

+0

將所有返回的結果放在一個數組中,並將其發送回去,使用合併功能是沒有必要的 –