嗨我正在嘗試創建一個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」
}
}
]
}
實際的API只是流溢沒有任何自動換行。我插入換行符以使其更清晰。 – user1904273