Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON_ENCODE of multidimensional array giving different results

Tags:

When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example:

$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4)); json_encode($arrytest) 

gives a single array of multiple json objects

[{"a":1,"b":2},{"c":3},{"d":4}]; 

whereas simply assigning a name to the middle array

$arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4)); json_encode($arrytest) 

creates a single json object with multiple json objects inside

{"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}}; 

why would the 1st option not return the same reasults as the 2nd execpt with "1" in place of "secondarray"

like image 362
dangel Avatar asked May 28 '12 02:05

dangel


People also ask

What does json_encode return?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What is json_encode and Json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What is json_encode used for?

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


1 Answers

In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.

If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.

$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));  // Force the outer structure into an object rather than array echo json_encode($arrytest , JSON_FORCE_OBJECT);  // {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}} 
like image 161
Michael Berkowski Avatar answered Oct 12 '22 11:10

Michael Berkowski