user882670
user882670

Reputation:

PHP: Convert array to JSON

myArray is:

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
)

I want to convert this into JSON, like:

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

I tried:

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

But this is returning:

[{"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}}

Upvotes: 2

Views: 149

Answers (1)

vp_arth
vp_arth

Reputation: 14982

Your issue is non-sequencial indexes.
Php array must have indexes 0..array.length-1 to be encoded to JSON array.

You can reset array keys with array_values:

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

Upvotes: 5

Related Questions