PHP将数组转换为JSON

时间:2016-03-20 22:30:04

标签: php arrays json

我有一个看起来像这样的数组

Array
(
    [0] => Array
        (
            [string] => something
            [name] => test
            [int] => 1
        )
    [1] => Array
        (
            [string] => another
            [name] => test2
            [int] => 43
        )
)

我想将其转换为特定的JSON布局,如下所示

[
    {
        "string": "something",
        "name": "test",
        "int": "1"
    },
    {
        "string": "another",
        "name": "test2",
        "int": "43"
    }
]

问题在于,当我使用内置的PHP函数json_encode时,我的输出看起来不像我想要的那样但是看起来像这样

{"0":{"string":"something","name":"test","int":1},"1":{"string":"another","name":"test2","int":43}}

基本上有没有办法从转换中删除索引?

1 个答案:

答案 0 :(得分:0)

请尝试以下代码段:

$data = [];
$data[0] = array(
    "string" => "something",
    "name" => "test",
    "int" => 1
);
$data[1] = array(
    "string" => "another",
    "name" => "test2",
    "int" => 43
);

echo json_encode($data);

输出:

[{"string":"something","name":"test","int":1},{"string":"another","name":"test2","int":43}]