在PHP中创建JSON数组

时间:2015-12-14 03:14:14

标签: php arrays json

我需要在PHP中创建这个JSON数组。如果我echo这个:

{"SUCCESS":[{"message":"Your Accout Info","AccoutInfo":{"credit":"$56.98USD","mail":"mail@me.com","currency":"USD"}}],"apiversion":"2.3.1"}

上面的echo代码可以正常工作。

构建数组的以下代码不起作用:

    header('Content-type:application/json;charset=utf-8');
    $data[SUCCESS] = array(
        'credit'   => '$56.98USD',
        'mail' => 'mail@me.com',
        'message' => 'Your Accout Info',
        'currency' => 'USD',
        'apiversion' => '2.3.1'  
    );

    echo json_encode($data);

我在这里缺少什么? 感谢

更新

我已将代码更新为:

    $data = array('SUCCESS' => array(
        'message'   => 'Your Accout Info',
        'AccoutInfo' => array(
        'credit' => '$56.98USD',
        'mail' => 'me@mail.com',
        'currency' => 'USD'),
        'apiversion' => '2.3.1')
   );

现在我得到了这个结果:

{"SUCCESS":{"message":"Your Accout Info","AccoutInfo":{"credit":"$56.98USD","mail":"me@mail.com","currency":"USD"},"apiversion":"2.3.1"}}

但我需要这个结果:

{"SUCCESS":[{"message":"Your Accout Info","AccoutInfo":{"credit":"$56.98USD","mail":"me@mail.com","currency":"USD"}}],"apiversion":"2.3.1"}

有什么建议可以解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

变化

 $data[SUCCESS] = array(...

 $data["SUCCESS"] = array(

答案 1 :(得分:1)

首先创建$data,它可以是对象或数组,并使用SUCCESS作为字符串'SUCCESS'而不是未定义的常量。

header('Content-type:application/json;charset=utf-8');
$data = array('SUCCESS' => array(
        array(
            'AccoutInfo' => array(
                'credit'   => '$56.98USD',
                'mail' => 'mail@me.com',
                'currency' => 'USD'
            ),
            'message' => 'Your Accout Info',
        )
    ),
    'apiversion' => '2.3.1'  
);

echo json_encode($data);

你的硬编码json和你尝试构建的结构是非常不同的

答案 2 :(得分:0)

更改为

$data = array('SUCCESS' => array(
        'credit'   => '$56.98USD',
        'mail' => 'mail@me.com',
        'message' => 'Your Accout Info',
        'currency' => 'USD',
        'apiversion' => '2.3.1'  
    )
);

echo json_encode($data);

答案 3 :(得分:0)

最后我得到了它的工作: - )

<?php
    header('Content-type:application/json;charset=utf-8');
    $data = Array
    (
        'SUCCESS' => Array
            (
                '0' => Array
                    (
                        'message' => 'Your Accout Info',
                        'AccoutInfo' => Array
                            (
                                'credit' => '$56.98USD',
                                'mail' => 'me@mail.com',
                                'currency' => 'USD'
                            )
                    )
            ),
        'apiversion' => '2.3.1'
        );

    echo json_encode($data);
?>

感谢@Musa指出我正确的方向。