JsonSerializable::jsonSerialize()函数是PHP中的内置函数,用于将JSON对象序列化为可以使用json_encode()函数本地化的值。
用法:
mixed JsonSerializable::jsonSerialize( void )
参数:该函数不接受任何参数。
返回值:该函数返回由json_encode()函数序列化的数据。
以下示例程序旨在说明PHP中的JsonSerializable::jsonSerialize()函数:
示例1:
class vector implements JsonSerializable {
public function __construct(array $arr) {
$this->array = $arr;
}
public function jsonSerialize() {
return $this->array;
}
}
// Declare an array
$arr = [1, 2, 3, 4, 5];
echo("JSON elements:\n");
// Convert the array element into JSON
echo json_encode(new vector($arr), JSON_PRETTY_PRINT);
?>
输出:
JSON elements:
[
1,
2,
3,
4,
5
]
示例2:
class vector implements JsonSerializable {
public function __construct(array $arr) {
$this->array = $arr;
}
public function jsonSerialize() {
return $this->array;
}
}
// Declare an array
$arr = [
"x" => "geeks",
"y" => "for",
"z" => "geeks"
];
echo("Convert the array element into JSON:\n");
// Convert the array element into JSON
echo json_encode(new vector($arr), JSON_PRETTY_PRINT);
?>
输出:
Convert the array element into JSON:
{
"x": "geeks",
"y": "for",
"z": "geeks"
}