json_encode 与 json_decode的区别

php中json_encode与json_decode的区别

相信刚开始接触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

    待解码的 jsonstring 格式的字符串。 这个函数仅能处理 UTF-8 编码的数据。Note: PHP implements a superset of JSON as specified in the original» RFC 7159.

  • assoc

    当该参数为 TRUE 时,将返回array 而非object

  • 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)
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值