您好,欢迎访问一九零五行业门户网

php 数组如何转换成json

php数组转换成json的方法:首先创建一个php示例文件;然后定义一个数组;最后通过“json_encode($arr);”方法将数组如何转换成json格式数据即可。
本教程操作环境:windows7系统、php5.6版,该方法适用于所有品牌电脑。
推荐:《php视频教程》
php数组转换成json的方法:
将 php 数组转换为 json 格式数据
<?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 函数函数描述
json_encode 对变量进行 json 编码
json_decode 对 json 格式的字符串进行解码,转换为 php 变量
json_last_error 返回最后发生的错误
json_encodephp json_encode()用于对变量进行 json 编码,该函数如果执行成功返回 json 数据,否则返回 false 。
语法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_object 以下实例演示了如何将 php 对象转换为 json 格式数据:
<?php class emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e);?>
以上代码执行结果为:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
json_decodephp json_decode() 函数用于对 json 格式的字符串进行解码,并转换为 php 变量。
语法mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
参数json_string: 待解码的 json 字符串,必须是 utf-8 编码数据
assoc: 当该参数为 true 时,将返回数组,false 时返回对象。
depth: 整数类型的参数,它指定递归深度
options: 二进制掩码,目前只支持 json_bigint_as_string 。
实例以下实例演示了如何解码 json 数据:
<?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)}
该方法适用于所有品牌的电脑。
以上就是php 数组如何转换成json的详细内容。
其它类似信息

推荐信息