0

ライブラリjson用にこのフォーマットでフォーマットしたい!jsGoJ は、次の形式の 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 ","メール":"office.asd@gmail.com","パスワード":"qwe123"},"1":{"id":"2","親":"1","ユーザー名": "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","パスワード":null},"5":{"id":"6","parent":"4","username":"Bole","email":null,"password":null},"6" :{"id":"7","parent":"4","username":"Vlada","email":null,"password":null}}"Bole","email":null,"password":null},"6":{"id":"7","parent":"4","username":"Vlada","email": null,"パスワード":null}}"Bole","email":null,"password":null},"6":{"id":"7","parent":"4","username":"Vlada","email": null,"パスワード":null}}

GoJsにはプロパティを定義する必要があるためid、置き換えようとしています。私のjsonは非常に異なっており、上記のjsonのように出力をフォーマットする必要がありますか?keykey

ここで何が間違っていますか?

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 に答える