Tools, FAQ, Tutorials:
json_encode() - PHP Associative Array to JSON Object
How to convert PHP Associative Arrays to JSON Objects using the json_encode() function?
✍: FYIcenter.com
Actually in PHP, all arrays are associative arrays.
If you create an array with regular array syntax and functions, PHP actually stores it as an associative array with the index number assigned to each elements as their keys.
We normally differentiate a regular array from an associative array by looking their keys:
When an array is processed by the json_encode() function, it will automatically detect the type of the array, and:
Here is a PHP example that shows you how to arrays are converted by json_decode():
<?php
# json_encode_associative_array.php
# Copyright (c) FYIcenter.com
$var = array(
"0"=>"dev.fyicenter.com",
"1"=>array("0"=>"PHP","1"=>"JSON")
);
print("\nInput: ");
var_dump($var);
print("Output: ".json_encode($var)."\n");
$var = array(
"site"=>"dev.fyicenter.com",
"topics"=>array("PHP"=>"Y","JSON"=>"Y")
);
print("\nInput: ");
var_dump($var);
print("Output: ".json_encode($var)."\n");
?>
If you run the above PHP code through the PHP engine, you get the following output:
>\fyicenter\php\php.exe json_encode_sociative_array.php
Input: array(2) {
[0]=>
string(17) "dev.fyicenter.com"
[1]=>
array(2) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "JSON"
}
}
Output: ["dev.fyicenter.com",["PHP","JSON"]]
Input: array(2) {
["site"]=>
string(17) "dev.fyicenter.com"
["topics"]=>
array(2) {
["PHP"]=>
string(1) "Y"
["JSON"]=>
string(1) "Y"
}
}
Output: {"site":"dev.fyicenter.com","topics":{"PHP":"Y","JSON":"Y"}}
⇒ json_encode() - JSON_PRETTY_PRINT Option
2023-08-17, ∼2359🔥, 0💬
Popular Posts:
What is Azure API Management Developer Portal? Azure API Management Developer Portal is an Azure Web...
How To Create an Array with a Sequence of Integers or Characters in PHP? The quickest way to create ...
How to use the "find-and-replace" Policy Statement for an Azure API service operation? The "find-and...
How to read Atom validation errors at w3.org? If your Atom feed has errors, the Atom validator at w3...
What's Wrong with "while ($c=fgetc($f)) {}" in PHP? If you are using "while ($c=fgetc($f)) {}" to lo...