关于json_encode和json_decode的理解

一、关于 PHP 语言来编码和解码 JSON 对象

1、json_encode(),json_decode()

简单来理解:

 json_encode() : 对变量进行编码

 json_decode() : 对变量进行解码

深入剖析:

json_encode(编码)

语法:string json_encode ( $value [, $options = 0 ] )

  • value: 要编码的值。该函数只对 UTF-8 编码的数据有效。
  • options:由以下常量组成的二进制掩码:JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJEC

示例1:

<?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}

  分析:将 PHP 数组转换为 JSON 格式数据

json_decode(解码)

语法:json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

示例:

<?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格式转化为数组或者对象形式

猜你喜欢

转载自blog.csdn.net/li3839/article/details/89297038