PHP/MYSQL/JSON: Simplify JSON for API


PHP/MYSQL/JSON: Simplify JSON for API

嗨,我正试图创建一个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”
            }
        }
    ]
}

您应该使用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;
}