相信刚开始接触php时大家对这两个词比较容易混淆,首先我们要明白这两个单词的意思
encode:编码 decode: 解码
再来看这两个函数
1. json_encode
说明
stringjson_encode ( mixed
$value
[, int$options
= 0 [, int$depth
= 512 ]] )返回字符串,包含了
value
值 JSON 形式的表示。编码受传入的
options
参数影响,此外浮点值的编码依赖于serialize_precision。
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); //{"a":1,"b":2,"c":3,"d":4,"e":5}
?>
2.json_decode
说明
mixedjson_decode ( string
$json
[, bool$assoc
= false [, int$depth
= 512 [, int$options
= 0 ]]] )接受一个 JSON 编码的字符串并且把它转换为 PHP 变量
参数
json
待解码的
json
string 格式的字符串。 这个函数仅能处理 UTF-8 编码的数据。Note: PHP implements a superset of JSON as specified in the original» RFC 7159.
assoc
depth
指定递归深度。
options
JSON解码的掩码选项。 现在有两个支持的选项。 第一个是JSON_BIGINT_AS_STRING, 用于将大整数转为字符串而非默认的float类型。第二个是JSON_OBJECT_AS_ARRAY, 与将
assoc
设置为TRUE 有相同的效果。
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
输出结果为
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)
}