您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php之JavaScript对象符号(JSON)

2025/8/21 13:35:39发布41次查看
自 php 5.2.0 起,json 扩展默认内置并编译进了 php。
json 序列化接口jsonserializable
实现 jsonserializable 的类可以 在 json_encode() 时定制他们的 json 表示法。
jsonserializable::jsonserialize — 指定需要被序列化成 json 的数据
example #1  返回一个数组
<?php class arrayvalue implements jsonserializable { public function __construct(array $array) { $this->array = $array; } public function jsonserialize() { return $this->array; } } $array = [1, 2, 3]; echo json_encode(new arrayvalue($array), json_pretty_print); ?>
以上例程会输出:
[ 1, 2, 3 ]
example #2 返回了一个关联数组
<?php class arrayvalue implements jsonserializable { public function __construct(array $array) { $this->array = $array; } public function jsonserialize() { return $this->array; } } $array = ['foo' => 'bar', 'quux' => 'baz']; echo json_encode(new arrayvalue($array), json_pretty_print); ?>
以上例程会输出:
{ "foo": "bar", "quux": "baz" }
example #3 返回一个整型数字
<?php class integervalue implements jsonserializable { public function __construct($number) { $this->number = (integer) $number; } public function jsonserialize() { return $this->number; } } echo json_encode(new integervalue(1), json_pretty_print); ?>
以上例程会输出:
1
example #4 返回一个字符串
<?php class stringvalue implements jsonserializable { public function __construct($string) { $this->string = (string) $string; } public function jsonserialize() { return $this->string; } } echo json_encode(new stringvalue('hello!'), json_pretty_print); ?>
以上例程会输出:
hello!
json 函数
json_decode — 对 json 格式的字符串进行编码
json_encode — 对变量进行 json 编码
json_last_error_msg — returns the error string of the last json_encode() or json_decode() call
json_last_error — 返回最后发生的错误
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product