Original: PHP JSON operations Summary
Since JSON can be used in many programming languages, we can use it for small data transfers, such as PHP output JSON strings for JavaScript. In PHP, you can use Json_decode () to parse a JSON object from a string of canonical strings, using Json_encode () to generate a string of canonical strings from a JSON object.
Example: <?php
$json = ' {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5} ';
Var_dump (Json_decode ($json));
Var_dump (Json_decode ($json, true));
Output:
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)
}
$arr = Array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);
echo Json_encode ($arr);
Output: {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}
1. Json_decode (), character representable json, is typically used when receiving data sent by JavaScript.
<?php
$s = ' {"WebName": "HOMEHF", "url": "Www.homehf.com", "contact": {"QQ": "744348666", "Mail": "[email protected]", "XX": " xxxxxxx "}}";
$web =json_decode ($s);
Echo ' website name: '. $web->webname. ' <br/> Website: '. $web->url. ' <br/> Contact information: qq-'. $web->contact->qq. ' MAIL: '. $web->contact->mail;
?>
In the example above, we first define a variable s, then parse it into a JSON object using Json_decode (), and then use it as JSON, which, from a usage perspective, is similar to the function of JSON and XML and array implementations, and can store some data that exists in relation to each other. But individuals feel that JSON is easier to use, and that data sharing can be achieved using JSON and JavaScript.
2. Json_encode (), JSON-to-character, which is typically used in AJAX applications to convert a JSON object into a string and output it to Javascript, and to store it in a database.
<?php
$s = ' {"WebName": "HOMEHF", "url": "Www.homehf.com", "contact": {"QQ": "744348666", "Mail": "[email protected]", "XX": " xxxxxxx "}}";
$web =json_decode ($s);
echo Json_encode ($web);
?>
Two. PHP JSON to Array
<?php
$s = ' {' webname ': ' homehf ', ' url ': ' www.homehf.com ', ' qq ': ' 744348666 '} ';
$web =json_decode ($s); Turn characters into JSON
$arr =array ();
foreach ($web as $k = $w) $arr [$k]= $w;
Print_r ($arr);
?>
In the above code, a JSON object has been turned into an array, but if it is nested JSON, the above code is obviously powerless, then we write a function to solve the nested JSON,
<?php
$s = ' {"WebName": "HOMEHF", "url": "Www.homehf.com", "contact": {"QQ": "744348666", "Mail": "[email protected]", "XX": " xxxxxxx "}}";
$web =json_decode ($s);
$arr =json_to_array ($web);
Print_r ($arr);
function Json_to_array ($web) {
$arr =array ();
foreach ($web as $k = = $w) {
if (Is_object ($w)) $arr [$k]=json_to_array ($W); The judging type is not an object
else $arr [$k]= $w;
}
return $arr;
}
?>
PHP JSON Operations Summary