Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_encode issue with array 0 key

Tags:

json

arrays

php

key

I am having a problem using json_encode to generate a json encoded string from an array.

The section of the array in question looks like this

RatingDistribution (Array, 11 elements)
    0 (Array, 1 element)
        0 (String, 3 characters ) 4.5
    1 (Array, 1 element)
        1 (String, 4 characters ) 11.9
    2 (Array, 1 element)

But produces this in the string:

"RatingDistribution":[["4.5"],{"1":"11.9"},

I would expect this:

"RatingDistribution":[{"0":"4.5"},{"1":"11.9"},

All I'm doing is this:

$result = json_encode($array);

Have I done something wrong or do I need more code to ensure the 0 key is present?

Cheers Andy

like image 386
andy_dodd Avatar asked Mar 08 '13 09:03

andy_dodd


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What does json_encode return?

json_encode — Returns the JSON representation of a value.

How check JSON array is empty or not in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


2 Answers

If you want to use arrays in your json then instead of JSON_FORCE_OBJECT parameter you can simply cast array to object.

Problem:

json_encode([0 => [1,2,3]]); // Return: [[1,2,3]]
json_encode(["0" => [1,2,3]]); // Return: [[1,2,3]]
json_encode([1 => [1,2,3]]); // Return: {"1":[1,2,3]}

Not what we expect :

json_encode([0 => [1,2,3]], JSON_FORCE_OBJECT); // Return: {"0":{"0":1,"1":2,"2":3}}

Solution:

json_encode((object)[0 => [1,2,3]]); // Return: {"0":[1,2,3]}
json_encode(new \ArrayObject([0 => [1,2,3]])); // Return: {"0":[1,2,3]}
like image 172
dmvslv Avatar answered Oct 21 '22 09:10

dmvslv


The result you are getting should be expected; json_encode detects that you are only using numeric keys in the array, so it translates that to an array instead of an object in JSON. Most of the time, that's exactly what you want to do.

If for some reason you don't (why?), in PHP >= 5.3 you can use the JSON_FORCE_OBJECT flag to get your desired output:

$result = json_encode($array, JSON_FORCE_OBJECT);
like image 27
Jon Avatar answered Oct 21 '22 08:10

Jon