Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force PHP json_encode() to encode indexes as strings

Tags:

json

php

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?

like image 588
bbeckford Avatar asked Dec 03 '22 01:12

bbeckford


1 Answers

Use JSON_FORCE_OBJECT:

json_encode( $data, JSON_FORCE_OBJECT );

Requires PHP 5.3+

like image 55
Esailija Avatar answered Dec 09 '22 16:12

Esailija