We are going to learn how to convert JSON in form of string to Array Object in PHP. An article convert PHP Array to JSON string is the opposite form which mean we can convert back and forth in different usage purpose. For today I will explain and give simple examples in order to understand how to convert JSON string to object array in PHP.
json_decode() - is built-in function to decode json string to PHP object.
Also read How to Use json_encode() in PHP
json_decode(string $json,bool $assoc = false,int $depth = 512,int $flag = 0): mixed
Return Value: if JSON cannot be decoded, NULL is returned. Return as Object or Array if encoded succeed.
Parameter | Type | Description |
---|---|---|
$json |
String (Required) | Value to be decode |
$assoc |
Boolean (Optional) | False will return as object, True will return as associative array |
$depth |
Integer (Optional) | Maximum recursion depth being decoded |
$flag |
Constant Integer (Optional) | Specifies a bitmask (JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR) |
Below examples will show the commonly use of json_decode()
method.
Example #1 - Convert Array Form in String to Real Array
<?php
// string form in array
$jobs = '["doctor","programmer","nurse","accountant","cashier"]';
//convert to real array php
$decode = json_decode($jobs);
//access value as array
echo $decode[0];
?>
Ouput #1
doctor
Example #2 - Convert JSON String to Object PHP
<?php
// String form in JSON object
$person = '{"name":"Sovary","job":"Developer","A-Z":"D"}';
// Convert to PHP Object
$decode = json_decode($person);
// show information in variable
print_r($decode);
// Access value by property
echo "My name is ".$decode->name." I am a ".$decode->job."\n";
echo "Access invalid property name=> ".$decode->{'A-Z'}
?>
Ouput #2
stdClass Object
(
[name] => Sovary
[job] => Developer
[A-Z] => D
)
My name is Sovary I am a Developer
Access invalid property name=> D
Example #3 - Convert Array JSON String to Associative Array PHP
<?php
// String form in JSON Array
$person = '[{"name":"Sovary","job":"Developer"},{"name":"Lin","job":"Accountant"}]';
// Convert to real multi dimension associative array
$decode = json_decode($person,true);
// Print info variable
print_r($decode);
// Access associative array
echo "My name is ".$decode[0]["name"]." I am a ".$decode[0]["job"];
?>
Ouput #3
Array
(
[0] => Array
(
[name] => Sovary
[job] => Developer
)
[1] => Array
(
[name] => Lin
[job] => Accountant
)
)
My name is Sovary I am a Developer
Thank you for read the article hope it would help your project. Have a nice day!
PHP
Founder 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