json_encode() 用于把 数组转换为 json数据格式
Example #1 A json_encode() 的例子
复制代码代码如下:
<?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}json_decode() 用于把 json数据转换为 对象或者 php数组
<?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)
}可以看出经过json_decode()编译出来的是对象,现在输出json_decode($data,true)
可以看出json_encode()和json_decode()是编译和反编译过程,注意json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号