php数组(array) 和 json相互转换函数:json_encode() 和 json_decode()

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 变量

 

json_encode() 和 json_decode()

 

php运行代码示例:

  1. <?php
  2. $arr=['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5,'f'=>6];//关联数组
  3. $arrtwo=['a','b','c','d','e','f'];//索引数组
  4. $json=json_encode($arr);
  5. var_dump($json);
  6. echo '<br>';
  7. $jsontwo=json_encode($arrtwo);
  8. var_dump($jsontwo);
  9. echo '<br>';
  10. var_dump($obj=json_decode($json));
  11. echo '<br>';
  12. var_dump(json_decode($jsontwo));
  13. echo '<br>';
  14. var_dump(get_object_vars($obj));//具体请查看:php对象和数组相互转换函数

 

php代码运行结果:

  1. string(37) "{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}"
  2. string(25) "["a","b","c","d","e","f"]"
  3. object(stdClass)#1 (6) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) ["f"]=> int(6) }
  4. 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" }
  5. 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对象和数组相互转换函数

    A+
所属分类:PHP函数
发布日期:2016年12月25日 23:49:53
最后更新时间:2021-03-27 15:50:53
付杰

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: