Today we learn about how to convert PHP array to object JSON string. We are going to convert PHP associate array to JSON. We will using json_encode() function to convert PHP array into JSON string, and convert single dimension array to JSON as well.
json_encode() - is a built-in function in PHP which is use to convert array to JSON object. We usually use this function when we are working with Ajax request which is send data back and forth via JSON.
json_encode(array $value, int $flags = 0, int $depth = 512): string|false
Return Value: Returns string if success convert, return false when failure.
Parameter | Type | Description |
---|---|---|
$value |
Any (Required) | Value to be encode |
$flag |
Constant Integer (Optional) | Specifies a bitmask (JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR) |
$depth |
Integer (Optional) | Set the maximum depth, value greater than zero |
Example #1
<?php
$jobs = ["doctor","programmer","nurse","accountant","cashier"];
//encode to string in array form
$jobsJSON = json_encode($jobs);
echo $jobsJSON;
?>
Ouput #1
["doctor","programmer","nurse","accountant","cashier"]
Example #2 - Using json_encode() with second parameter
<?php
$jobs = ["doctor","programmer","nurse","accountant","cashier"];
//encode to string in json form
$jobsJSON = json_encode($jobs,JSON_FORCE_OBJECT);
echo $jobsJSON;
?>
Ouput #2
{"0":"doctor","1":"programmer","2":"nurse","3":"accountant","4":"cashier"}
Example #3 - Encode associate array to json string
<?php
$jobs = ["name"=>"Nary","job"=>"doctor"];
//encode to string in json form
$jobsJSON = json_encode($jobs);
echo $jobsJSON;
?>
Ouput #3
{"name":"Nary","job":"doctor"}
Example #4 - Encode two dimensional associate array to array json string
<?php
$jobs = [
["name"=>"Nary","job"=>"doctor"],
["name"=>"Dara","job"=>"programmer"],
["name"=>"Lin","job"=>"nurse"]
];
//json array form in string
$jobsJSON = json_encode($jobs,JSON_PRETTY_PRINT);
echo $jobsJSON;
?>
Ouput #3
[
{
"name": "Nary",
"job": "doctor"
},
{
"name": "Dara",
"job": "programmer"
},
{
"name": "Lin",
"job": "nurse"
}
]
Thank you for read the article hope it would help your project. Have a nice day!
PHPFounder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him