bbeckford bbeckford - 2 years ago 117
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?

Answer Source


json_encode( $data, JSON_FORCE_OBJECT );

Requires PHP 5.3+

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download