自 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);
?>以上例程会输出:
立即学习“PHP免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
[
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);
?>以上例程会输出:
立即学习“PHP免费学习笔记(深入)”;
{
"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);
?>以上例程会输出:
立即学习“PHP免费学习笔记(深入)”;
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);
?>以上例程会输出:
立即学习“PHP免费学习笔记(深入)”;
"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 — 返回最后发生的错误
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号