dpd20130 2016-10-26 16:22
浏览 57
已采纳

GoJs的Php数据库格式json

I want to format json in this format for js library! GoJs expect json in this format:

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" }
                ];

In php i try to return json like above but am realy new to json and my example dont work!

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

My JSON looks like this:

{"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}}

I try to replace id with key becouse GoJs need key property defined. My json is so so different and i need to format output like above json?

What i do wrong here ?

  • 写回答

2条回答 默认 最新

  • duanhuan6336 2016-10-26 16:28
    关注

    You just need to change the way you store it in array

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

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序