2015-10-13 64 views
2

嗨我正在嘗試創建一個API,將數據庫調用的結果數組轉換爲可輕鬆解析的json。PHP/MYSQL/JSON:簡化API的JSON

使用簡單的命令json_encode,我的JSON是一個複雜的,詳細的嵌套對象和數組混亂的混亂,很難解析另一端。

任何人都可以建議一種方法,以削減應提供的關鍵信息:用戶ID,長評(lcom)和短評(shcom)以及如何將其作爲API發送?

在此先感謝您的任何建議

下面是從下面的查詢和代碼產生的電流JSON輸出:

$sql = "SELECT userid,shcom,lcom FROM comments WHERE userid = 1 LIMIT 4"; 
$res = mysql_query($sql) or die(mysql_error()); 
$comments = array(); 
while($row = mysql_fetch_array($res)) { 
$comments[] = array('row'=>$row); 
} 
echo json_encode(array('comments'=>$comments)); 

Json output: 
{ 
    "comments": [ 
     { 
      "row": { 
       "0": "1", 
       "userid": "1", 
       "1": "hello", 
       "shcom": "hello", 
       "2": "hellothere", 
       "lcom」: "hellothere" 
      } 
     }, 
     { 
      "row": { 
       "0": "1", 
       "userid": "1", 
       「1」: 」agreed」, 
       "shcom」: 」agreed」, 
       「2」: 」agreedforonce」, 
       "lcom」: 」agreedforonce」 
      } 
     }, 
     { 
      "row": { 
       "0": "1", 
       "userid": "1", 
       "1": "gohome", 
       "shcom」: 」gohome「, 
       「2」: 」gohomenow」, 
       "lcom: 」gohomenow」 
      } 
     }, 
     { 
      "row": { 
       "0": "1", 
       "userid": "1", 
       "1": "getout」, 
       "shcom」: 」getout」, 
       「2」: 」getoutofhere」, 
       "lcom: 」getoutofhere」 
      } 
     } 
    ] 
} 
+0

實際的API只是流溢沒有任何自動換行。我插入換行符以使其更清晰。 – user1904273

回答

2

您應該使用mysqli而不是mysql因爲mysql已被棄用。無論如何,代碼中的問題都是由於兩個原因而發生的。一,mysql_fetch_array不會產生你期待的結果。二,在你的迭代中,你不是以正確的方式提取答案。要解決此問題,請使用mysq_fetch_assoc並將每個$row都推送到最終陣列。

替換此:

while($row = mysql_fetch_array($res)) { 
    $comments[] = array('row'=>$row); 
} 

這樣:

while($row = mysql_fetch_assoc($res)) { 
    $comments[] = $row; 
} 
+0

工作。要清楚,因爲我對術語模糊不清,調用輸出[{「userid」:「1」,「shcom」:「hello」,「lcom」:「hello there」},{... },{...}]由一組字典組成的JSON對象?或者只是一個由數組組成的對象? – user1904273

+0

您的結果以JSON格式輸出**字符串**。然後,您可以將該字符串轉換爲Javascript中的JSON對象或PHP中的數組。 – CodeGodie