-1

我正在进行一个项目,必须使用 json 来实现我的目标。我正在使用 mysql 和使用 json_encode() 的 php。我怎么得到这个:

{"contacts": [ { "id": "c200","name": "Ravi Tamada","email": "ravi@gmail.com","address": "xx-xx-xxxx,x - street, x - country","gender" : "male","phone": { "mobile": "+91 0000000000","home": "00 000000","office": "00 000000"}},{ "id": "c201","name": "Johnny Depp","email": "johnny_depp@gmail.com","address": "xx-xx-xxxx,x - street, x - country","gender" : "male","phone": {"mobile": "+91 0000000000","home": "00 000000","office": "00 000000"}},

长成这样?

{
"contacts": [
    {
            "id": "c200",
            "name": "Ravi Tamada",
            "email": "ravi@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    },
    {
            "id": "c201",
            "name": "Johnny Depp",
            "email": "johnny_depp@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
    }
            ]
};

我知道这是可以做到的,因为当多个教程“回显”对象时,json 对象看起来像这样,就像这个http://api.androidhive.info/contacts/。我使用了错误的功能吗?这是我的代码。

$employee = array();
while($employee = mysql_fetch_array($result, MYSQL_ASSOC)) {
$employee[] = array('employee'=>$employee);
}

$output = json_encode(array('employee' => $employee));

}
4

1 回答 1

2

JSON_PRETTY_PRINT选项设置为手册页上的名称。

$output = json_encode(array('employee' => $employee), JSON_PRETTY_PRINT);

不过,我不建议将其用于生产:它会增加文件大小。

于 2012-08-10T09:07:18.320 回答