json_encode不会生成我需要的JSON表单

时间:2013-02-18 21:36:51

标签: php json

我无法获得有关jquery脚本的有效响应。

我的回复:

{
    "success": true,
    "data": {
        "attack": null,
        "shield": null,
        "speed": null,
        "cargo": null,
        "upg_slots": "1"
    }
}

代码:

echo json_encode(array(
    'success' => true,
    'data' => array(
        'attack' => null,
        'shield' => null,
        'speed' => null,
        'cargo' => null,
        'upg_slots' => "1"
    )
));

有效回复:

{
    "success": true,
    "data": [
        {
            "attack": null,
            "shield": null,
            "speed": null,
            "cargo": null,
            "upg_slots": "1"
        }
    ]
}

提前致谢!

2 个答案:

答案 0 :(得分:1)

看起来您在响应中的'data'键下缺少了一个数组,只需将其重新包装如下:

 echo json_encode(array('success' => true, 'data' => array(array( 'attack' => null, 'shield' => null, 'speed' => null, 'cargo' => null, 'upg_slots' => "1"))));
//                                                    ^^^

答案 1 :(得分:1)

如果您需要包含单个字典的列表,则需要将关键字数组嵌套在位置数组中:

$data = array(
    array(
        'attack' => null,
        'shield' => null,
        'speed' => null,
        'cargo' => null,
        'upg_slots' => "1"
    )
);
echo json_encode(array('success' => true, 'data' => $data));