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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)