0

我想以json这种格式为js库格式化!GoJ 期望采用这种格式的 json:

model.nodeDataArray =
                [
                    { key: "1",              username: "Don Meow",   source: "cat1.png" },
                    { key: "2", parent: "1", username: "Demeter",    source: "cat2.png" },
                    { key: "3", parent: "1", username: "Copricat",   source: "cat3.png" },
                    { key: "4", parent: "3", username: "Jellylorum", source: "cat4.png" },
                    { key: "5", parent: "3", username: "Alonzo",     source: "cat5.png" },
                    { key: "6", parent: "2", username: "Munkustrap", source: "cat6.png" }
                ];

在 php 中,我尝试像上面一样返回 json,但我对 json 真的很陌生,我的示例不起作用!

$users = $db->query("SELECT * FROM user");
$data = array();

while ($result = $users->fetch_assoc())
{
    $data['key'] = $result['id'];
    $data['username'] = $result['username'];
    $data['email'] = $result['email'];
    $data['parent'] = $result['parent'];

    array_push($data, $result);
}

echo json_encode($data);

我的 JSON 看起来像这样:

{"key":"7","username":"Vlada","parent":"4","0":{"id":"1","parent":null,"username":"Ivan ","email":"office.asd@gmail.com","password":"qwe123"},"1":{"id":"2","parent":"1","username": "Martinu","email":"asd@gmail.com","password":"qwe123"},"2":{"id":"3","parent":"1","username": "Biljana","email":"asd.com","password":"qwe123"},"3":{"id":"4","parent":"2","username":"Emil ","电子邮件":"test@test.com","password":null},"4":{"id":"5","parent":"2","username":"Elena","email":"test@test.com","password ":null},"5":{"id":"6","parent":"4","username":"Bole","email":null,"password":null},"6" :{"id":"7","parent":"4","username":"Vlada","email":null,"password":null}}"伯乐","email":null,"password":null},"6":{"id":"7","parent":"4","username":"Vlada","email":空,“密码”:空}}"伯乐","email":null,"password":null},"6":{"id":"7","parent":"4","username":"Vlada","email":空,“密码”:空}}

我尝试替换id为因为keyGoJs 需要key定义属性。我的 json 是如此不同,我需要像上面的 json 那样格式化输出?

我在这里做错了什么?

4

2 回答 2

3

您只需要更改将其存储在数组中的方式

$users = $db->query("SELECT * FROM user");
$data = array();

while ($result = $users->fetch_assoc())
{
$row = array (
    "key" => $result['id'],
    "username" => $result['username'],
    "email" => $result['email'],
    "parent" => $result['parent'],
);

array_push($data, $row);
}

echo json_encode($data);
于 2016-10-26T16:28:16.570 回答
1

你在这里做一些奇怪的事情

尝试将其简化为

$users = $db->query("SELECT * FROM user");
$data = array();
while ($row = $users->fetch_assoc())
{
    $t = array();
    $t['key']       = $row ['id'];
    $t['username']  = $row ['username'];
    $t['email']     = $row ['email'];
    $t['parent']    = $row ['parent'];

    $data[] = $t;
}

或者更简单,在查询中指定你想要的列,这将使它更快,然后你就可以构建你的数组

$users = $db->query("SELECT id,username,email,parent FROM user");
$data = array();
while ($row = $users->fetch_assoc())
{
    $data[] = $row;
}
于 2016-10-26T16:30:42.620 回答