bbeckford bbeckford - 1 year ago 69
PHP Question

Force PHP json_encode() to encode indexes as strings

I have a an array setup as follows:

$myArray = array();
$myArray[] = "New array item 1";
$myArray[] = "New array item 2";
$myArray[] = "New array item 3";

When I run json_encode() on it it outputs the following:

["New array item 1","New array item 2","New array item 3"]

What I want is for the function to encode the indexes as strings:

["0":"New array item 1","1":"New array item 2","2":"New array item 3"]

So that later I can remove say the first item without affecting the index of the second.

Is there an easy way to do this?



json_encode( $data, JSON_FORCE_OBJECT );

Requires PHP 5.3+