Php 用于 GoJ 的数据库格式 json

Php database format json for GoJs

我想为 js 库以这种格式格式化 json! GoJs 期望 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 中,我尝试像上面那样 return 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","email":"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}}

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

我做错了什么?

你只需要改变你在数组中的存储方式

$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);

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

尝试将其简化为

$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;
}