4

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?

0

3 Answers 3

10

Use JSON_FORCE_OBJECT:

json_encode( $data, JSON_FORCE_OBJECT );

Requires PHP 5.3+

Sign up to request clarification or add additional context in comments.

6 Comments

Is there no other way? I wanted to keep it as an array.
@bbeckford what do you mean? You'll still have the original array, it is not mutated or removed
Well for instance I wouldn't be able to do this would I? $decodedArray = json_decode('{"0":"New array item 1","1":"New array item 2","2":"New array item 3"}'); $decodedArray[] = "New array item 4"; json_encode( $decodedArray, JSON_FORCE_OBJECT );
@bbeckford If you're planning to use this array in JavaScript, it's best to know that the syntax doesn't allow Arrays with such indexes anyway. You'll get a SyntaxError: Unexpected token :.
@bbeckford you should pass true as second parameter to json_decode
|
4

Not exactly what you want but you can use JSON_FORCE_OBJECT option:

json_encode($myArray, JSON_FORCE_OBJECT);

which would produce:

{"0":"New array item 1","1":"New array item 2","2":"New array item 3"}

Same if you cast your array to object:

json_encode((object)$myArray);

Alternatively:

$myArray = array(
  "0" => "New array item 1",
  "2" => "New array item 2",
  "3" => "New array item 3"
  );

 echo json_encode($myArray);

would give same:

{"0":"New array item 1","2":"New array item 2","3":"New array item 3"}

3 Comments

This works only if indexes are not continous. "When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair."
@morgar: Read the manual again. It works for all cases because that's what JSON_FORCE_OBJECT is for.
5.3 release date is 30 June 2009, so what argument is that?
3

For PHP < 5.3 , use this method :

<?php   

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

echo json_encode((object)$myArray); // typecast the array as object

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.