json_encode
json_encode — 对变量进行 JSON 编码;数组转成json格式;
说明
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
返回 value 值的 JSON 形式
json_decode
json_decode — 对 JSON 格式的字符串进行编码;json格式转成数组;
说明
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
php运行代码示例:
- <?php
- $arr=['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5,'f'=>6];//关联数组
- $arrtwo=['a','b','c','d','e','f'];//索引数组
- $json=json_encode($arr);
- var_dump($json);
- echo '<br>';
- $jsontwo=json_encode($arrtwo);
- var_dump($jsontwo);
- echo '<br>';
- var_dump($obj=json_decode($json));
- echo '<br>';
- var_dump(json_decode($jsontwo));
- echo '<br>';
- var_dump(get_object_vars($obj));//具体请查看:php对象和数组相互转换函数
php代码运行结果:
- string(37) "{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}"
- string(25) "["a","b","c","d","e","f"]"
- object(stdClass)#1 (6) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) ["f"]=> int(6) }
- array(6) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" [4]=> string(1) "e" [5]=> string(1) "f" }
- array(6) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) ["f"]=> int(6) }
由于上面有关联数组转成json的时候是string类型,但是再把这个string类型的json格式字符串转成数组,它却是一个对象类型;因此:需要把对象先转换成数组才可以去做其它的,比如说数组循环;有人说对象也可以循环,但是不建议,对象循环的效率没有数组高;因此PHP很多地方都是用的数组;
具体请查看:php对象和数组相互转换函数;





