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!
PHPAs the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him