php之JavaScript對象符號(JSON)

來源:互聯網
上載者:User
自 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 — 返回最後發生的錯誤

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.