小编典典

PHP:将数组转换为JSON

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}}

阅读 519

收藏
2020-07-27

共1个答案

小编典典

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

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

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