Compare the differences between json_encode and json_decode
Four basic principles of JSON
1.json_decode()
json_decode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_decode — Characters in JSON format String encoding
Description
mixed json_decode (string $json [, bool $assoc])
Accepts a JSON format string and converts it into a PHP variable
Parameters
json
The string in json string format to be decoded.
assoc
When this parameter is TRUE, array will be returned instead of object.
Return value
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
Example
Example #1 json_decode Example of ()
Copy the code as follows:
$json = '{"a":1,"b":2 ,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above example will output:
Copy the code as follows:
object(stdClass)#1 ( 5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a" ] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int (4)
["e"] => int(5)
}
Copy the code code as follows:
$data='[{"Name":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1" ,"Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000", "QQNo":""}]';
echo json_decode($data);
The result is:
Copy the code as follows:
Array ( [0] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) )
It can be seen that the objects compiled by json_decode() are now output as json_decode ($data,true) Try
Copy the code as follows:
echo json_decode($data,true);
Result:
Copy the code code as follows:
Array ( [0] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) )
It can be seen that json_decode($data,true) outputs an associative array. It can be seen that json_decode($data) outputs an object, and json_decode("$arr",true) forces it to generate a PHP associative array.
2.json_encode()
json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_encode — JSON the variable Encoding
Report a bug Description
string json_encode (mixed $value [, int $options = 0 ] )
Return the JSON form of value
Report a bug Parameters
value
The value to be encoded can be any data type except resource type
This function can only accept UTF-8 encoded data
options
Binary mask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.
Report a bug Return value
Encoding If successful, a JSON format is returned. Represents a string or returns FALSE on failure.
Report a bug Update log
Version Description
5.4.0 options parameter constants added: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE.
5.3.3 The options parameter adds a constant: JSON_NUMERIC_CHECK.
5.3.0 Add options parameter.
Report a bug Example
Example #1 A json_encode() example
Copy code code as follows:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4, 'e'=>5);
echo json_encode($arr);
?>
The above routine will output:
Copy code The code is as follows:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example #2 Usage of options parameter in json_encode() function
Copy the code The code is as follows:
php
$a = array('
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a, JSON_HEX_APOS ), "\n";
echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n" ;
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\ n\n";
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo " Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\ n";
$d = array('foo' => 'bar', 'baz' => 'long');
echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>
The above routine will output:
Copy the code as follows:
Normal: ["
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\""," &blong&","\u00e9"]
Apos: ["
Quot: ["
Amp: ["
Unicode: ["
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object : {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz ":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}
Example #3 Continuous and Non-consecutive array example
Copy the code as follows:
echo "Continuous array".PHP_EOL;
$sequential = array( "foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);
echo PHP_EOL. "Nonsequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);
echo PHP_EOL."A non-continuous array generated by deleting a continuous array value".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
?>
The above routine will output:
Copy the code code as follows:
Continuous array
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3 ) "bar"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
string (27) "["foo","bar","baz","blong"]"
Non-continuous array
array(4) {
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
[ 4]=>
string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz ","4":"blong"}"
A non-continuous array generated by deleting a continuous array value
array(3) {
[0]=>
string (3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"
Copy the code as follows:
$obj->Name= 'a1';$obj->Number ='123';
$obj->Contno= '000';
echo json_encode($obj);
The result is:
Copy the code as follows:
{" Name":"a1",
"Number":"123",
"Contno":"000"
}
You can see json_encode() and json_decode() are the compilation and decompilation process. Note that json only accepts utf-8 encoded characters, so the parameters of json_encode() must be utf-8 encoded, otherwise you will get empty characters or null.
json
The string in json string format to be decoded.
assoc
When this parameter is TRUE, array will be returned instead of object.
Return value
Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
Example
Example #1 json_decode Example of ()
Copy the code as follows:
$json = '{"a":1,"b":2 ,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The above example will output:
Copy the code as follows:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int( 1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Copy the code The code is as follows:
$data='[{"Name ":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno" :"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000","QQNo":""}]';
echo json_decode($data);
The result is:
Copy the code as follows:
Array ( [0] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => stdClass Object ( [Name] => a1 [Number] => ; 123 [Contno] => 000 [QQNo] => ) [2] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] = > ) )
It can be seen that the object compiled by json_decode() is an object. Now try to output json_decode($data,true)
Copy the code as follows:
echo json_decode($data,true);
Result:
Copy the code as follows:
Array ( [ 0] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) )
It can be seen that json_decode($data,true) outputs an associative array. From this, it can be seen that json_decode($data) outputs an object, and json_decode("$arr",true) forces it to generate a PHP associative array. .
2.json_encode()
json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_encode — Yes Variables are JSON encoded
Report a bug Description
string json_encode (mixed $value [, int $options = 0 ] )
Return the JSON form of value
Report a bug Parameters
value
The value to be encoded can be any data type except the resource type
This function can only accept UTF-8 encoded data
options
Binary mask consisting of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.
Report a bug Return value
If encoding is successful, return one A string represented as JSON or FALSE on failure.
Report a bug Update log
Version Description
5.4.0 options parameter constants added: JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE.
5.3.3 The options parameter adds a constant: JSON_NUMERIC_CHECK.
5.3.0 Add options parameter.
Report a bug Example
Example #1 A json_encode() example
Copy the code as follows:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=> 4,'e'=>5);
echo json_encode($arr);
?>
The above routine will output:
Copy code The code is as follows:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example #2 Usage of options parameter in json_encode() function
Copy the code as follows:
$a = array('
echo "Normal: ", json_encode($a), "\ n";
echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n"; #$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode( $b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
$ d = array('foo' => 'bar', 'baz' => 'long');
echo "Associative array always output as object: ", json_encode($d), "\ n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>
The above routine Will output:
Normal: ["
Tags: ["\u003Cfoo\u003E ","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["
Quot: ["
Amp: ["
Unicode: ["
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\ u0026blong\u0026","é"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[ 1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}
Example #3 Example of continuous and non-continuous arrays
Copy the code as follows:
echo "Continuous Array" .PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);
echo PHP_EOL."Nonsequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz" , 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);
echo PHP_EOL."Delete a continuous array value Non-continuous array generated by ".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
? >
The above routine will output:
Copy the code as follows:
Continuous array
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(3 ) "baz"
[3]=>
string(5) "blong"
}
string(27) "["foo","bar","baz","blong "]"
Non-continuous array
array(4) {
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
[4]=>
string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"
Delete one A non-continuous array generated by the method of continuous array values
array(3) {
[0]=>
string(3) "foo"
[2]=>
string (3) "baz"
[3]=>
string(5) "blong"
}
string(33) "{"0":"foo","2": "baz","3":"blong"}"
Copy the code. The code is as follows:
$obj->Name= 'a1'; $obj->Number ='123';
$obj->Contno= '000';
echo json_encode($obj);
The result is:
Copy the code as follows:
{"Name":"a1",
"Number":"123",
"Contno":"000"
}
It can be seen that json_encode() and json_decode() are compilation and decompilation processes. Note that json only accepts utf-8 encoded characters, so the parameters of json_encode() must be utf-8 encoded. , otherwise you will get an empty character or null.
The above is the detailed content of Compare the differences between json_encode and json_decode. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
