PHP擴展之JavaScript對象符號(JSON)
自 PHP 5.2.0 起,JSON 擴展默認內(nèi)置并編譯進了 PHP。
JSON 序列化接口JsonSerializable實現(xiàn)?JsonSerializable?的類可以 在?json_encode()?時定制他們的 JSON 表示法。
JsonSerializable::jsonSerialize?—?指定需要被序列化成 JSON 的數(shù)據(jù)
Example #1 ?返回一個數(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);?>
以上例程會輸出:
[ 1, 2, 3]
Example #2 ?返回了一個關(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);?>
以上例程會輸出:
{ 'foo': 'bar', 'quux': 'baz'}
Example #3 ?返回一個整型數(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);?>
以上例程會輸出:
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 函數(shù)json_decode?— 對 JSON 格式的字符串進行編碼json_encode?— 對變量進行 JSON 編碼json_last_error_msg?— Returns the error string of the last json_encode() or json_decode() calljson_last_error?— 返回最后發(fā)生的錯誤
相關(guān)文章:
1. asp(vbscript)中自定義函數(shù)的默認參數(shù)實現(xiàn)代碼2. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)3. jsp EL表達式詳解4. jsp中sitemesh修改tagRule技術(shù)分享5. JavaWeb Servlet中url-pattern的使用6. 爬取今日頭條Ajax請求7. 如何使用瀏覽器擴展篡改網(wǎng)頁中的JS 文件8. ASP基礎(chǔ)知識VBScript基本元素講解9. ASP刪除img標簽的style屬性只保留src的正則函數(shù)10. JSP servlet實現(xiàn)文件上傳下載和刪除
