JSON_ENCODE of multidimensional array giving different results
JSON_ENCODE is a function that converts a PHP data structure, such as an array, into a JSON (JavaScript Object Notation) string. When encoding a multidimensional array, the function will convert each sub-array into a JSON object.
For example, consider the following PHP array:
<?php
$data = [
"name" => "John Doe",
"address" => [
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA",
"zip" => "12345",
],
"phone numbers" => [
"home" => "555-555-5555",
"work" => "555-555-5556",
],
];
When using json_encode on this array, it will return a JSON string:
<?php
$data = [
"name" => "John Doe",
"address" => [
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA",
"zip" => "12345",
],
"phone numbers" => [
"home" => "555-555-5555",
"work" => "555-555-5556",
],
];
$json = json_encode($data);
echo $json;
After executing the code, you can see the sub-arrays "address" and "phone numbers" have been converted into JSON objects.
It is important to note that json_encode will only convert arrays that are "indexed" (i.e., have numeric keys) into JSON arrays. Associative arrays (i.e., arrays with string keys) will be encoded as objects.
Additionally, json_encode has some options that can be passed as its second argument, such as JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_NUMERIC_CHECK, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE and etc.
for example, using JSON_PRETTY_PRINT will make the encoded json string more human-readable:
<?php
$data = [
"name" => "John Doe",
"address" => [
"street" => "123 Main St",
"city" => "Anytown",
"state" => "CA",
"zip" => "12345",
],
"phone numbers" => [
"home" => "555-555-5555",
"work" => "555-555-5556",
],
];
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
will output:
{ "name": "John Doe", "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" }, "phone numbers": { "home": "555-555-5555", "work": "555-555-5556" } }