Tools, FAQ, Tutorials:
json_decode() - JSON Object to PHP Associative Array
How to convert JSON Objects to PHP Associative Arrays using the json_decode() function?
✍: FYIcenter.com
Actually, JSON Objects match better with PHP Associative Arrays than PHP Objects.
You can force json_decode() function to turn return PHP Associative Arrays
for any JSON Objects by giving the second argument as "true".
Default of the second argument is "false".
There are different ways to access properties in the output PHP associative array:
Here is a PHP example that shows you how to access properties from the associative array returned by json_decode():
<?php
# json_decode_associative_array.php
# Copyright (c) FYIcenter.com
$json = '{"site":"dev.fyicenter.com","topics":{"PHP":"Y","JSON":"Y"}}';
print("\nInput: ".$json."\n");
# Decoded into an array
$array = json_decode($json,true);
print("\nOutput Array:\n");
print(" Type: ".gettype($array)."\n");
print(" Size: ".count($array)."\n");
print(" ['site']: ".$array["site"]."\n");
print(" ['topics']['JSON']: ".$array["topics"]["JSON"]."\n");
# Dump the array
print("\nOutput Array Dump:\n");
var_dump($array);
# Decoded into an object
$obj = json_decode($json,false);
print("\nOutput Object:\n");
print(" Type: ".gettype($obj)."\n");
print(" ->site: ".$obj->site."\n");
print(" ->topics->JSON: ".$obj->topics->JSON."\n");
# Dump the object
print("\nOutput Object Dump:\n");
var_dump($obj);
?>
If you run the above PHP code through the PHP engine, you get the following output:
>\fyicenter\php\php.exe json_decode_sociative_array.php
Input: {"site":"dev.fyicenter.com","topics":{"PHP":"Y","JSON":"Y"}}
Output Array:
Type: array
Size: 2
['site']: dev.fyicenter.com
['topics']['JSON']: Y
Output Array Dump:
array(2) {
["site"]=>
string(17) "dev.fyicenter.com"
["topics"]=>
array(2) {
["PHP"]=>
string(1) "Y"
["JSON"]=>
string(1) "Y"
}
}
Output Object:
Type: object
->site: dev.fyicenter.com
->topics->JSON: Y
Output Object Dump:
object(stdClass)#1 (2) {
["site"]=>
string(17) "dev.fyicenter.com"
["topics"]=>
object(stdClass)#2 (2) {
["PHP"]=>
string(1) "Y"
["JSON"]=>
string(1) "Y"
}
}
⇒ json_last_error_msg() - PHP JSON Error Message
2018-03-04, ∼6227🔥, 0💬
Popular Posts:
Where can I download the EPUB 2.0 sample book "The Metamorphosis" by Franz Kafka? You can following ...
How to access Request body from "context.Request.Body" object in Azure API Policy? Request body is t...
How to run PowerShell Commands in Dockerfile to change Windows Docker images? When building a new Wi...
How to use the "@(...)" expression in Azure API Policy? The "@(...)" expression in Azure API Policy ...
How to Instantiate Chaincode on BYFN Channel? You can follow this tutorial to Instantiate Chaincode ...