PHP:将数组转换为JSON

时间:2014-04-01 17:04:58

标签: php json

myArray是:

Array
(
    [1] => 0
    [2] => 11970.99
    [3] => 2888
    [4] => 0
    [5] => 1500
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
    [12] => 0
)

我想将其转换为JSON,例如:

[{"name":"Recebimentos","data":[0,11970.99,2888,0,1500,0,0,0,0,0,0,0]}

我试过了:

echo json_encode(array(
            array(name=> 'Recebimentos', data=>$myArray),
        ));

但这又回来了:

[{"name":"Recebimentos","data":{"1":0,"2":11970.99,"3":2888,"4":0,"5":1500,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}}

1 个答案:

答案 0 :(得分:3)

您的问题是非顺序索引 Php数组必须具有要编码为JSON数组的索引0..array.length-1

您可以使用array_values重置数组键:

echo json_encode(array(
  array(name=> 'Recebimentos', data=>array_values($myArray)),
));