GoJs的{php}数据库格式json

时间:2016-10-26 16:22:37

标签: php mysql json gojs

我想以json库的格式格式化js! 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中我尝试像上面一样返回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看起来像这样:

  

{ “键”: “7”, “用户名”: “Vlada”, “亲本”: “4”, “0”:{ “ID”: “1”, “亲本”:NULL, “用户名” : “伊万”, “电子邮件”: “office.asd@gmail.com”, “密码”: “qwe123”}, “1”:{ “ID”: “2”, “亲本”: “1”,”用户名 “:” 马丁努 “ ”电子邮件“: ”asd@gmail.com“, ”密码“: ”qwe123“}, ”2“:{ ”ID“: ”3“, ”亲本“: ”1“,”用户名 “:” 普拉夫希奇”, “电子邮件”: “asd.com”, “密码”: “qwe123”}, “3”:{ “ID”: “4”, “亲本”: “2”, “用户名” : “埃米尔”, “电子邮件”: “test@test.com”, “密码”:NULL} “4”:{ “ID”: “5”, “亲本”: “2”, “用户名”:”埃琳娜”, “电子邮件”: “test@test.com”, “密码”:空}, “5”:{ “ID”: “6”, “父”: “4”, “用户名”: “伯乐” , “电子邮件”:NULL, “密码”:空}, “6”:{ “ID”: “7”, “亲本”: “4”, “用户名”: “Vlada”, “电子邮件”:NULL,”密码“:空}}

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

我在这里做错了什么?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

尝试将其简化为

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