PHP擴(kuò)展之JavaScript對(duì)象符號(hào)(JSON)
自 PHP 5.2.0 起,JSON 擴(kuò)展默認(rèn)內(nèi)置并編譯進(jìn)了 PHP。
JSON 序列化接口JsonSerializable實(shí)現(xiàn)?JsonSerializable?的類(lèi)可以 在?json_encode()?時(shí)定制他們的 JSON 表示法。
JsonSerializable::jsonSerialize?—?指定需要被序列化成 JSON 的數(shù)據(jù)
Example #1 ?返回一個(gè)數(shù)組
<?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);?>
以上例程會(huì)輸出:
[ 1, 2, 3]
Example #2 ?返回了一個(gè)關(guān)聯(lián)數(shù)組
<?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);?>
以上例程會(huì)輸出:
{ 'foo': 'bar', 'quux': 'baz'}
Example #3 ?返回一個(gè)整型數(shù)字
<?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);?>
以上例程會(huì)輸出:
1
Example #4 返回一個(gè)字符串
<?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);?>
以上例程會(huì)輸出:
'Hello!'JSON 函數(shù)json_decode?— 對(duì) JSON 格式的字符串進(jìn)行編碼json_encode?— 對(duì)變量進(jìn)行 JSON 編碼json_last_error_msg?— Returns the error string of the last json_encode() or json_decode() calljson_last_error?— 返回最后發(fā)生的錯(cuò)誤
相關(guān)文章:
1. 一款功能強(qiáng)大的markdown編輯器tui.editor使用示例詳解2. 利用CSS制作3D動(dòng)畫(huà)3. Python+unittest+requests 接口自動(dòng)化測(cè)試框架搭建教程4. Springboot 全局日期格式化處理的實(shí)現(xiàn)5. Python 實(shí)現(xiàn)勞拉游戲的實(shí)例代碼(四連環(huán)、重力四子棋)6. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)7. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程8. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法9. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼10. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))
