Convert Array to JSON using json_encode code snippet
<?php
//A multi-dimensional associative array for employee data.
$employee_data = array(
"Benjamin" => array("Age"=>25,"Department"=>"Marketing","Work Experience (In Years)"=>3),
"Mark" => array("Age"=>29,"Department"=>"Finance","Work Experience (In Years)"=>5),
"Sophie" => array("Age"=>27,"Department"=>"IT","Work Experience (In Years)"=>4)
);
//Echo the output of the json_encode function.
echo json_encode($employee_data);
?>
What is JSON?
JSON stands for Javascript Object Notation. In simplest terms, JSON is a data interchange format. It means that an application can send and retrieve data in JSON. Although the JSON is syntactically similar to javascript objects syntax, it is in no way restricted to javascript. JSON is an independent format for exchanging data between a client and a server.
Why use JSON?
JSON is a common choice these days for data interchange for several reasons. First of all, it is lightweight, self-describing, and an easy to understand data interchange format. Secondly, it is language-independent, and almost every language has built-in functions to parse and translate it.
How does JSON look like?
JSON can be communicated in a text format back and forth between computers or client/server in particular. As mentioned already, JSON follows javascript object syntax that is in the form of key value pairs. Here’s an example of a JSON string.
‘{“id”: 1, “name”: “Robert”, “role”:”Manager”}’
You can see how intuitive a JSON is. The JSON in the example carries information about an employee. It has three key value pairs.
Key | Value |
id | 1 |
name | Robert |
role | Manager |
In real-world applications, JSON strings can be comprehensive. Nevertheless, it is never a hassle to parse and translate a JSON because almost every programming language supports it.
PHP and JSON
PHP natively supports JSON. It has a JSON extension that provides useful functions to convert data from JSON to PHP format and vice versa. These functions are readily available for use in PHP without any additional configurations or imports.
The two most important functions for conversion between the two data formats are:
- json_encode (array to json in PHP)
- json_decode (json to array in PHP)
In this article about array to JSON PHP, we will explore PHP json_encode function. First, we will review its syntax and then use it in code for more clarity.
Converting Arrays to JSON in PHP with json_encode
As seen above, json_encode converts array to JSON in PHP. Let’s review this function from PHP documentation.
Description
json_encode returns JSON representation of a value.
Function Signature
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Arguments
$value – Array to be converted into JSON
$flags – A constant for altering the behaviour of the function. (See note)
$depth – Defines the maximum depth or levels to parse in a multi-dimensional array
Return Type
It returns a JSON encoded string on success or false otherwise
Note
The $flags argument defines certain constants that are needed to alter the behaviour of the encoder. PHP defines a comprehensive list of these constants. We will see a couple of these flags in the following examples to demonstrate their use.
Example #1-Array to JSON PHP using json_encode
The example simply converts an array to JSON in PHP without using any additional flags. Let’s see how.
<?php
//A multi-dimensional associative array for employee data.
$employee_data = array(
"Benjamin" => array("Age"=>25,"Department"=>"Marketing","Work Experience (In Years)"=>3),
"Mark" => array("Age"=>29,"Department"=>"Finance","Work Experience (In Years)"=>5),
"Sophie" => array("Age"=>27,"Department"=>"IT","Work Experience (In Years)"=>4)
);
//Echo the output of the json_encode function.
echo json_encode($employee_data);
?>
Here’s the output.
{"Benjamin":{"Age":25,"Department":"Marketing","Work Experience (In Years)":3},"Mark":{"Age":29,"Department":"Finance","Work Experience (In Years)":5},"Sophie":{"Age":27,"Department":"IT","Work Experience (In Years)":4}}
PHP prints the JSON to the console. However, it is not clearly readable. One way to format it is to use a flag, JSON_PRETTY_PRINT. Let’s see how.
<?php
//A multi-dimensional associative array for employee data.
$employee_data = array(
"Benjamin" => array("Age"=>25,"Department"=>"Marketing","Work Experience (In Years)"=>3),
"Mark" => array("Age"=>29,"Department"=>"Finance","Work Experience (In Years)"=>5),
"Sophie" => array("Age"=>27,"Department"=>"IT","Work Experience (In Years)"=>4)
);
//Echo the output of the json_encode function.
echo json_encode($employee_data, JSON_PRETTY_PRINT);
?>
The output now becomes
{
"Benjamin": {
"Age": 25,
"Department": "Marketing",
"Work Experience (In Years)": 3
},
"Mark": {
"Age": 29,
"Department": "Finance",
"Work Experience (In Years)": 5
},
"Sophie": {
"Age": 27,
"Department": "IT",
"Work Experience (In Years)": 4
}
}
Looks crisp. That’s the power of using a flag. Did you see it alter the behaviour of the encoder? There are many other flags but we will see only a few. If you want to go a step further then read more about these flags in the PHP documentation.
Array to JSON PHP using json_encode (JSON_NUMERIC_CHECK)
One important flag in the json_encode function is the JSON_NUMERIC_CHECK. With this flag enabled, the json_encode converts string representing numbers automatically to numbers. Let’s see this through an example.
<?php
//A multi-dimensional associative array for employee data.
$employee_data = array("2020","+2021","-2022","1.4e3","0.0002");
//Echo the output of the json_encode function without JSON_NUMERIC_CHECK flag.
echo json_encode($employee_data).PHP_EOL;
//Echo the output of the json_encode function with JSON_NUMERIC_CHECK flag.
echo json_encode($employee_data, JSON_NUMERIC_CHECK);
////OUTPUT (Without JSON_NUMERIC_CHECK flag)
//["2020","+2021","-2022","1.4e3","0.0002"]
//OUTPUT (With JSON_NUMERIC_CHECK flag)
//[2020,2021,-2022,1400,0.0002]
?>
See the difference between the outputs with and without the JSON_NUMERIC_CHECK flag. With the flag, json_encode converts the string numbers into actual numbers, even the one in exponential form. On the contrary, json_encode encodes the string as it is without any type conversions.
Example#3 – Array to JSON PHP using json_encode (Combining Flags)
This example shows a PHP array containing a symbol, URL, and number. We will use several flags together to get a real clean JSON encoded output. You should pay close attention to the output with and without flags.
<?php
$array = ["Symbol"=>'€',"URL"=> 'http://fuelingPHP.com/how-to-make-an-associative-array-in-php/', "Number"=>'337'];
$bad_output = json_encode($array);
$good_output = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES |JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT);
echo $bad_output.PHP_EOL;
echo $good_output;
// $bad_output is {"Symbol":"\u20ac","URL":"http:\/\/fuelingPHP.com\/how-to-make-an-associative-array-in-php\/","Number":"337"}
// $good_output is
// {
// "Symbol": "€",
// "URL": "http://fuelingPHP.com/how-to-make-an-associative-array-in-php/",
// "Number": 337
// }
?>
That seems like hundred problems, one solution. Each of these flags has an interpretation, summarized in the table below.
CONSTANT | DESCRIPTION |
JSON_UNESCAPED_UNICODE | Encode unicode characters literally. (Example: \u20ac to €) |
JSON_UNESCAPED_SLASHES | Don’t escape / |
JSON_NUMERIC_CHECK | Encodes numeric strings as numbers |
JSON_PRETTY_PRINT | Pretty print the JSON encoded output. |
Conclusion
Phew! We have covered a lot of ground in this article. By now, we expect that you have understood what is JSON, its purpose and use. Moreover, you’re now familiar with conversion from array to JSON in PHP. We hope that you have enjoyed the article. Stay tuned for more informative content about PHP.
Want to explore more useful PHP tutorials?
We have many fun articles related to PHP. You can explore these to learn more about PHP.